How to validate radio button using javascript

client-side-validation, javascript, validation

Solution

1st: If you know that your code isn't right, you should fix it before do anything!

You could do something like this:

function validateForm() {
    var radios = document.getElementsByName("yesno");
    var formValid = false;

    var i = 0;
    while (!formValid && i < radios.length) {
        if (radios[i].checked) formValid = true;
        i++;        
    }

    if (!formValid) alert("Must check some option!");
    return formValid;
}​

See it in action: http://jsfiddle.net/FhgQS/

Problem

Need to validate a radio button input, i.e. when submit button is pressed and no radio buttons have been selected, it alerts the user saying 'please select a check box', and if a radio button has been selected then simply submit the form, needs no alert. Can only use HTML CSS and JavaScript for this, I know it's 1000 times easier in jquery but sadly I can't use that. And I know my HTML isn't valid, but unless it directly affects my current problem then I'll handle it later. ``` <form name="form1" action="#" onsubmit="return validateForm()" method="post"> First time visitor?:<br/> <label for="s1">Yes</label> <input type="radio" id="1" name="yesno" value="1"/> <br/> <label for="s2">No</label> <input type="radio" id="1" name="yesno" value="2"/> <br/> <input type="submit" value="Submit"><br/> </form> ``` Any pointers are greatly appreciated, thanks.

Original source

Related problems