[英]Redirecting conditionally based on radio button
I would like to know if there is a way in HTML5 to take a user to a particular page based on what the user chooses for a radio button selection using HTML5. 我想知道HTML5中是否有一种方法可以根据用户使用HTML5选择单选按钮的选择,将用户带到特定页面。
For example if the user chooses the "male" radio button and hits submit, then I want to take him to .../male.html
or if female is chosen and then submit is clicked then take her to .../female.html
例如,如果用户选择“男性”单选按钮并单击“提交”,那么我想将他带到.../male.html
或者如果选择了女性然后单击“提交”,则将她带到.../female.html
If its not possible to do this in HTML5, I could figure something out in javascript despite my lack of experience with that language. 如果无法在HTML5中做到这一点,尽管我缺乏使用该语言的经验,但我还是可以在javascript中弄清楚。 However, I don't know how I would implement the code to only run when submit is pressed, could you give me a little guidance? 但是,我不知道如何实现仅在按下Submit时才能运行的代码,您能给我一些指导吗?
As a sidenote, I don't wish to use any jQuery or other libraries. 附带说明,我不希望使用任何jQuery或其他库。 I want it to be either HTML5 if possible, or plain javascript. 我希望它尽可能是HTML5或纯JavaScript。
HTML(5): HTML(5):
<form id="form">
<input type="radio" name="gender" id="gender-male" value="Male" />
<input type="radio" name="gender" id="gender-female" value="Female" />
</form>
JS(5): JS(5):
var submit = function (e) {
if (e.preventDefault) {
e.preventDefault();
}
if (document.getElementById('gender-male').checked) {
window.location = 'male.html';
} else if (document.getElementById('gender-female').checked) {
window.location = 'female.html';
}
return false;
};
window.onload = function () {
var form = document.getElementById('form');
if (form.attachEvent) {
form.attachEvent('submit', submit);
} else {
form.addEventListener('submit', submit);
}
}
Have created a jsfiddle to demonstrate how it could be done with HTML and Javascript. 已经创建了一个jsfiddle来演示如何使用HTML和Javascript完成它。 There's no way to do it with just HTML. 仅凭HTML无法做到这一点。
http://jsfiddle.net/benwong/W4FVC/ http://jsfiddle.net/benwong/W4FVC/
HTML HTML
<input id="MaleRadio" type="radio" name="sex" value="male" checked="checked">male</input>
<input id="FemaleRadio" type="radio" name="sex" value="female">female</input>
<input id="SubmitButton" type="submit" value="submit" />
Javascript 使用Javascript
var maleRadio = document.getElementById("MaleRadio"),
femaleRadio = document.getElementById("FemaleRadio"),
submitButton = document.getElementById("SubmitButton");
submitButton.addEventListener("click", function () {
if (maleRadio.checked) {
alert('male');
window.location = "male.html";
} else {
alert('female');
window.location = "female.html";
}
}, false);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.