简体   繁体   中英

Radio Button check in vanilla javascript is not working

My radio button checking is not working. Can anyone please help me with this? I want to check if the radio button is checked or not. if not checked then I want this program to give an alert. But in this program whenever the radio button is not checked I am not getting the alert.

 <div>
              <label for="gender">Gender: </label>
              <input type="radio" name="myRadio"> Male
              <input type="radio" name="myRadio"> Female
              <input type="radio" name="myRadio"> Other
          </div>

The radio button checking function is given below:

function radioCheck(){
              var radio = document.forms["myForm"]["myRadio"].value;
    
                  for (var i=0; i<radio.length; i++) {
                    if (radio[i].checked){
                    break;
                  }else
                  {
                    alert("No radio button is checked");
                  }
              }
    
        }

Okay so this is working code:

function radioCheck(){
  const radioList = document.getElementsByName("myRadio")
  let notChecked = false;
  
  for(let i = 0; i < radioList.length; i ++){
    if(radioList[i].checked){
        return;
    } else {
        notChecked = true;
    }
   
  }

   if(notChecked){
      alert("No radio button is checked")
    }
}

radioCheck()

To explain:

  • first of all you have to get all inputs by using document.getElementsByName because the only one thing that they have the same is name property which is name="myRadio" in this example
  • second thing I added variable notChecked which is false on initial so when it will go through all inputs and see that one of them is not selected if will show alert
  • then you just do normal for loop that goes through all elements and checks if they are checked
  • if one of them is checked it just stops for loop and returns nothing, otherwise it sets notChecked = true
  • after loop I just check if notChecked value is true and if it is it shows an alert
  • last and important thing - you have to run this function at least once to execute it so you just add radioCheck() in the end
  • I also added this part in html <button onclick={radioCheck()} > run again </button>

so after clicking on button "run again" you can use it again (just for test)

here is working example:

link

hope that my answer will help you out:) if you have any questions please ask

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