Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript validation for radio button are not working

Suppose i have this piece of my html code

<!--Marital Status-->
            <div class="gap">
                <table>
                    <tr class="parent">
                        <td>Martial Status:</td>
                        <td>&emsp;
                            <input type="radio" id="rad1" name="Status" value="1">
                            <label for="Single">Single</label>
                            <br>&emsp;
                            <input type="radio" id="rad2" name="Status" value="2">
                            <label for="Married">Married</label>
                        </td>
                    </tr>
                </table>
            </div>

and for the javascript

function validateForm() {
var status = document.getElementsByName("Status");
var validradio = false;
var i = 0;
  while(!validradio && i < status.length){
    if(status[i].checked) validradio = true;
    }
    i++;

  if (!validradio){
    alert("Please select your marital status");
    return false;
  }
}

when i try the validation without checking the radio button, the page become not responsive and the alert box didn’t pop up as it should. But when i checked one of the checkbox, the page turn out just find. May i know, what’s going on?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’ve misaligned one statement in the javascript, change it to:

function validateForm() {
    var status = document.getElementsByName("Status");
    var validradio = false;
    var i = 0;
    while(!validradio && i < status.length){
        if(status[i].checked) validradio = true;
        i++;
    }
    if (!validradio){
        alert("Please select your marital status");
        return false;
    }
}

With i++ outside of the loop, i forever remained at value 0.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading