0

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?

3
  • 2
    you cannot have the same ID multiple times! Commented Apr 3, 2017 at 15:30
  • id="flip" => class="flip" -- $("#flip") => $(".flip") 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. Commented Apr 3, 2017 at 15:35

4 Answers 4

3

get value by name not id :

$("input[name='flip']:checked").val();
Sign up to request clarification or add additional context in comments.

Comments

2

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();

1 Comment

It should be this I guess.. This gave me result not your's.. please check $("input[name='flip']:checked").val();
0

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

2 Comments

then what is the solution to this?
Use an attribute selector instead [name="flip"].
0

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.