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?

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • 2
    you cannot have the same ID multiple times! – Luke Apr 03 '17 at 15:30
  • `id="flip"` => `class="flip"` -- `$("#flip")` => `$(".flip")` – Funk Forty Niner Apr 03 '17 at 15:30
  • 1
    [ID's Must Be Unique](http://stackoverflow.com/questions/5611963/can-multiple-different-html-elements-have-the-same-id-if-theyre-different-eleme), specifically because it will cause problems in [JavaScript](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id) and CSS when you try to interact with those elements. – Jay Blanchard Apr 03 '17 at 15:35

4 Answers4

3

get value by name not id :

$("input[name='flip']:checked").val();
Abanoub Makram
  • 463
  • 2
  • 13
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();
brk
  • 48,835
  • 10
  • 56
  • 78
  • It should be this I guess.. This gave me result not your's.. please check `$("input[name='flip']:checked").val();` –  Apr 03 '17 at 15:37
0

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

Luke
  • 8,235
  • 3
  • 22
  • 36
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"

Sudipto
  • 440
  • 2
  • 8