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

前端 未结 28 2497
面向向阳花
面向向阳花 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 02:01

    You can use this simple script. You may have multiple radio buttons with same names and different values.

    var checked_gender = document.querySelector('input[name = "gender"]:checked');
    
    if(checked_gender != null){  //Test if something was checked
    alert(checked_gender.value); //Alert the value of the checked.
    } else {
    alert('Nothing checked'); //Alert, nothing was checked.
    }
    

提交回复
热议问题