Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

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

Here is my code:

<table>
   <tr>
      <td>Sales Promotion</td>
      <td><input type="radio" name="q12_3" value="1">1</td>
      <td><input type="radio" name="q12_3" value="2">2</td>
      <td><input type="radio" name="q12_3" value="3">3</td>
      <td><input type="radio" name="q12_3" value="4">4</td>
      <td><input type="radio" name="q12_3" value="5">5</td>
   </tr>
</table>
<button id="submit">submit</button>

Here is JS:

$(function(){
    $("#submit").click(function(){      
        alert($('input[name=q12_3]').val());
    });
 });

Here is JSFIDDLE! Every time I click button it returns 1. Why? Can anyone help me?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
  <tr>
    <td>Sales Promotion</td>
    <td><input type="radio" name="q12_3" value="1">1</td>
    <td><input type="radio" name="q12_3" value="2">2</td>
    <td><input type="radio" name="q12_3" value="3">3</td>
    <td><input type="radio" name="q12_3" value="4">4</td>
    <td><input type="radio" name="q12_3" value="5">5</td>
  </tr>
</table>
<button id="submit">submit</button>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...