admin管理员组

文章数量:1391925

I have these radio buttons.

<input type="radio" id="flip" name="flip" value="Head" checked="checked" /> Head
<input type="radio" id="flip" name="flip" value="Tail"  /> Tail

I am trying to process a form with ajax for which I tried to get the value of these radio buttons with this

var dataString = {
    flip: $("#flip").val()
};
console.log(dataString.flip);

Now when I do console.log to check the value its sending I am always getting Head and not Tail even if I select Tail as a choice. Can anyone help me as why is it so?

I have these radio buttons.

<input type="radio" id="flip" name="flip" value="Head" checked="checked" /> Head
<input type="radio" id="flip" name="flip" value="Tail"  /> Tail

I am trying to process a form with ajax for which I tried to get the value of these radio buttons with this

var dataString = {
    flip: $("#flip").val()
};
console.log(dataString.flip);

Now when I do console.log to check the value its sending I am always getting Head and not Tail even if I select Tail as a choice. Can anyone help me as why is it so?

Share Improve this question edited Apr 3, 2017 at 15:33 Funk Forty Niner 74.2k15 gold badges70 silver badges143 bronze badges asked Apr 3, 2017 at 15:28 user6224087user6224087 3
  • 2 you cannot have the same ID multiple times! – Luke Commented Apr 3, 2017 at 15:30
  • id="flip" => class="flip" -- $("#flip") => $(".flip") – Funk Forty Niner Commented Apr 3, 2017 at 15:30
  • 1 ID's Must Be Unique, specifically because it will cause problems in JavaScript and CSS when you try to interact with those elements. – Jay Blanchard Commented Apr 3, 2017 at 15:35
Add a ment  | 

4 Answers 4

Reset to default 3

get value by name not id :

$("input[name='flip']:checked").val();

id cannot be duplicate. It need to be unique.In this case you can use name attribute

Use name to select get the selected radio button value

$("input:radio[name=flip]:checked").val();

you cannot have the same ID multiple times! that is the reaon why it only displays one of the two.

ID #flip is an unique element(you cannot have more than more #flip element). Use .flip instead of #flip.

And also change id="flip" to class="flip"

本文标签: javascriptGet Radio Button value with jqueryAjaxStack Overflow