jQuery get value of selected radio button

前端 未结 27 1869
耶瑟儿~
耶瑟儿~ 2020-11-22 13:55

The problem statement is simple. I need to see if user has selected a radio button from a radio group. Every radio button in the group share same id.

The problem is

27条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 14:21

    First, you cannot have multiple elements with the same id. I know you said you can't control how the form is created, but...try to somehow remove all the ids from the radios, or make them unique.

    To get the value of the selected radio button, select it by name with the :checked filter.

    var selectedVal = "";
    var selected = $("input[type='radio'][name='s_2_1_6_0']:checked");
    if (selected.length > 0) {
        selectedVal = selected.val();
    }
    

    EDIT

    So you have no control over the names. In that case I'd say put these radio buttons all inside a div, named, say, radioDiv, then slightly modify your selector:

    var selectedVal = "";
    var selected = $("#radioDiv input[type='radio']:checked");
    if (selected.length > 0) {
        selectedVal = selected.val();
    }
    

提交回复
热议问题