javascript 在选择的电台上,重定向到一个链接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8681505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
on select radio, redirect to a link
提问by Anju Thapa
I have three radios and i want onselect of anyone to be redirected to a link. Using javascript or jquery
我有三个收音机,我希望选择任何人都可以重定向到一个链接。使用 javascript 或 jquery
All <input name="EventRadio" type="radio" value="" checked="checked"/>
Events<input name="EventRadio" type="radio" value="Events" /> Classes<input name="EventRadio" type="radio" value="Classes"/><br /><br />
so since "All" is default checked, i want it to go to mysite.com/search.aspx. now if user selects Events, I want to redirect user to mysite.com/search?type=Events or if user selects Classes, I want to redirect the user to mysite.com/search?type=Classes as response to the onselect of the radios. How do I achieve this?
因此,由于“全部”是默认选中的,我希望它转到 mysite.com/search.aspx。现在,如果用户选择事件,我想将用户重定向到 mysite.com/search?type=Events 或者如果用户选择类,我想将用户重定向到 mysite.com/search?type=Classes 作为对 onselect 的响应收音机。我如何实现这一目标?
回答by Ramesh Kotha
All <input name="EventRadio" type="radio" value="" checked="checked" onclick ="goToLocation(this.value)"/>
Events <input name="EventRadio" type="radio" value="Events" onclick ="goToLocation(this.value)"/>
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";
}
回答by David says reinstate Monica
As a demonstration:
作为示范:
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';
}
}
}
Please note that I've also changed your mark up to use <label>
elements, and removed the
s and <br />
s.
请注意,我还更改了您的标记以使用<label>
元素,并删除了
s 和<br />
s。
回答by maxedison
$('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';
}
});