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

前端 未结 28 2812
面向向阳花
面向向阳花 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条回答
  •  Happy的楠姐
    2020-11-22 01:58

    There is very sophisticated way you can validate whether any of the radio buttons are checked with ECMA6 and method .some().

    Html:

    
    
    

    And javascript:

    let htmlNodes = document.getElementsByName('status');
    
    let radioButtonsArray = Array.from(htmlNodes);
    
    let isAnyRadioButtonChecked = radioButtonsArray.some(element => element.checked);
    

    isAnyRadioButtonChecked will be true if some of the radio buttons are checked and false if neither of them are checked.

提交回复
热议问题