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

前端 未结 28 2799
面向向阳花
面向向阳花 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条回答
  •  萌比男神i
    2020-11-22 01:55

    A vanilla JavaScript way

    var radios = document.getElementsByTagName('input');
    var value;
    for (var i = 0; i < radios.length; i++) {
        if (radios[i].type === 'radio' && radios[i].checked) {
            // get value, set checked flag or do whatever you need to
            value = radios[i].value;       
        }
    }
    

提交回复
热议问题