How can I check whether a radio button is selected with JavaScript?

前端 未结 28 2770
面向向阳花
面向向阳花 2020-11-22 00:58

I have two radio buttons within an HTML form. A dialog box appears when one of the fields is null. How can I check whether a radio button is selected?

28条回答
  •  离开以前
    2020-11-22 01:59

    Here is the solution which is expanded upon to not go ahead with submission and send an alert if the radio buttons are not checked. Of course this would mean you have to have them unchecked to begin with!

    if(document.getElementById('radio1').checked) {
    } else if(document.getElementById('radio2').checked) {
    } else {
      alert ("You must select a button");
      return false;
    }
    

    Just remember to set the id ('radio1','radio2' or whatever you called it) in the form for each of the radio buttons or the script will not work.

提交回复
热议问题