How to loop through a radio buttons group without a form?

后端 未结 3 1441
死守一世寂寞
死守一世寂寞 2021-02-02 12:44

How do I loop through a radio buttons group without a form in JavaScript or jQuery?

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-02 13:14

    ...in case someone wants to do this without jQuery (since it was part of the question):

    I'm not sure what you mean by without a form. If you mean you don't want to pass the form element to a javascript function, you could do it like this:

    for (var i = 0; i < document.form_name.radio_name.length; i++) {
        if (document.form_name.radio_name[i].checked) {
            // ...
        }
    }
    

    If you mean without a form as in you have no form node, you could wrap them in a span (or a div) and use code like this:

    var span = document.getElementById("span_id");
    var inputs = span.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; ++i) {
        if (inputs[i].checked) {
            // ...
        }
    }
    

提交回复
热议问题