How to get the selected radio button’s value?

后端 未结 18 1913
北海茫月
北海茫月 2020-11-22 00:57

I’m having some strange problem with my JS program. I had this working properly but for some reason it’s no longer working. I just want to find the value of the radio button

18条回答
  •  半阙折子戏
    2020-11-22 01:07

    If it is possible for you to assign a Id for your form element(), this way can be considered as a safe alternative way (specially when radio group element name is not unique in document):

    function findSelection(field) {
        var formInputElements = document.getElementById("yourFormId").getElementsByTagName("input");
        alert(formInputElements);
            for (i=0; i < formInputElements.length; i++) {
            if ((formInputElements[i].type == "radio") && (formInputElements[i].name == field) && (formInputElements[i].checked)) {
                alert(formInputElements[i].value + ' you got a value');     
                return formInputElements[i].value;
            }
        }
    }
    

    HTML:

提交回复
热议问题