在选择广播,重定向到链接

时间:2011-12-30 16:18:17

标签: javascript jquery radio onselect

我有三个无线电,我想要选择任何人重定向到一个链接。使用javascript或jquery

    All <input name="EventRadio" type="radio" value="" checked="checked"/>&nbsp;
    Events<input name="EventRadio" type="radio" value="Events" />&nbsp;Classes<input name="EventRadio" type="radio" value="Classes"/><br /><br />

所以由于默认选中“全部”,我希望它转到mysite.com/search.aspx。 现在如果用户选择事件,我想将用户重定向到mysite.com/search?type=Events 或者如果用户选择Classes,我想将用户重定向到mysite.com/search?type=Classes  作为对无线电的选择的回应。我如何实现这一目标?

3 个答案:

答案 0 :(得分:3)

All     <input name="EventRadio" type="radio" value="" checked="checked" onclick ="goToLocation(this.value)"/>&nbsp;
Events  <input name="EventRadio" type="radio" value="Events" onclick ="goToLocation(this.value)"/>&nbsp;
Classes <input name="EventRadio" type="radio" value="Classes" onclick ="goToLocation(this.value)"/><br /><br />


function goToLocation(val){
 if(val == "Events")
     window.location = "go to Events location";
 if(val == "Classes")
     window.location = "go to Classes location";
window.location = "go to default location";

}

答案 1 :(得分:1)

作为示范:

var inputs = document.getElementsByTagName('input'),
    radios = [],
    output = document.getElementById('output'),
    url = 'mysite.com/search?type=';

for (var i = 0, len = inputs.length; i<len; i++) {
    if (inputs[i].type == 'radio'){
        radios.push(inputs[i]);
    }
}

for (var r=0, leng = radios.length; r<leng; r++){
    radios[r].onchange = function(){
        if (this.value){
            /* in real life use:
            document.location = url + this.value;
            */
            output.innerHTML = url + this.value;
        }
        else {
            /* in real life use:
            document.location = 'mysite.com/search?type=Events';
            */
            output.innerHTML = 'mysite.com/search.aspx';
        }
    }
}

JS Fiddle demo

请注意,我还更改了您的标记以使用<label>元素,并删除了&nbsp;<br />

答案 2 :(得分:0)

$('input').click(function(){
    var val = $(this).val();
    if(val !== ''){
        window.location = 'http://mysite.com/search?type=' + val;
    }else{
        window.location = 'http://mysite.com/search.aspx';
    }
});