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

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

    Just trying to improve on Russ Cam's solution with some CSS selector sugar thrown in with the vanilla JavaScript.

    var radios = document.querySelectorAll('input[type="radio"]:checked');
    var value = radios.length>0? radios[0].value: null;
    

    No real need for jQuery here, querySelectorAll is widely supported enough now.

    Edit: fixed a bug with the css selector, I've included the quotes, although you can omit them, in some cases you can't so it's better to leave them in.

提交回复
热议问题