Home > OS >  Javascript validation for radio button are not working
Javascript validation for radio button are not working

Time:12-14

Suppose i have this piece of my html code

<!--Marital Status-->
            <div >
                <table>
                    <tr >
                        <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?

CodePudding user response:

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.

CodePudding user response:

This can be simplified immensly. Use querySelectorAll with an attribute selector and the :checked pseudo class and count the result

function validateForm() {
  
  //Use an attribute selector with :checked to get the number of selected  
  if (document.querySelectorAll("[name=Status]:checked").length < 1;) {
    alert("Please select your marital status");
    return false;
  }
}

document.getElementById("validate").addEventListener("click", validateForm);
<div >
  <table>
    <tr >
      <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>
<button id="validate">Validate</button>

  • Related