简体   繁体   中英

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.

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

If its not possible to do this in HTML5, I could figure something out in javascript despite my lack of experience with that language. 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?

As a sidenote, I don't wish to use any jQuery or other libraries. I want it to be either HTML5 if possible, or plain javascript.

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):

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. There's no way to do it with just HTML.

http://jsfiddle.net/benwong/W4FVC/

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM