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

前端 未结 28 2443
面向向阳花
面向向阳花 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:55

    If you want vanilla JavaScript, don't want to clutter your markup by adding IDs on each radio button, and only care about modern browsers, the following functional approach is a little more tasteful to me than a for loop:

    If neither is checked, it will return undefined (though you could change the line above to return something else, e.g., to get false returned, you could change the relevant line above to: }).pop() || {value:false}).value;).

    There is also the forward-looking polyfill approach since the RadioNodeList interface should make it easy to just use a value property on the list of form child radio elements (found in the above code as formElement[radioName]), but that has its own problems: How to polyfill RadioNodeList?

提交回复
热议问题