In jQuery, how do I get the value of a radio button when they all have the same name?

前端 未结 7 983
[愿得一人]
[愿得一人] 2020-11-28 04:44

Here is my code:

Sales Promotion
7条回答
  •  孤城傲影
    2020-11-28 04:51

    In your code, jQuery just looks for the first instance of an input with name q12_3, which in this case has a value of 1. You want an input with name q12_3 that is :checked.

    $("#submit").click(() => {
      const val = $('input[name=q12_3]:checked').val();
      alert(val);
    });
    
    
    
    Sales Promotion 1 2 3 4 5

    Note that the above code is not the same as using .is(":checked"). jQuery's is() function returns a boolean (true or false) and not (an) element(s).


    Because this answer keeps getting a lot of attention, I'll also include a vanilla JavaScript snippet.

    document.querySelector("#submit").addEventListener("click", () => {
      const val = document.querySelector("input[name=q12_3]:checked").value;
      alert(val);
    });
    Sales Promotion 1 2 3 4 5

提交回复
热议问题