-1

How can I get the selected radio button value via jQuery? I tried:

var selectedPlan = $("input[name=Plan[packageId]]:checked'").val();
alert(selectedPlan);

bBt didn't work.

<td style="vertical-align: top;">
    <input type="radio" value="1" name="Plan[packageId]">
    <lable>3 Games</lable><br>

    <input type="radio" value="2" name="Plan[packageId]">
    <lable>5 Games</lable><br>

    <input type="radio" value="3" name="Plan[packageId]">
    <lable>10 Games</lable><br>
</td>

here is the fiddle http://jsfiddle.net/vk3z45an/

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
dev1234
  • 5,376
  • 15
  • 56
  • 115
  • Open your console : `Uncaught Error: Syntax error, unrecognized expression: input[name=Plan[packageId]]:checked' ` – Jeremy Thille May 21 '15 at 07:03
  • There plenty of suggestions on this one: http://stackoverflow.com/questions/596351/how-can-i-get-which-radio-is-selected-via-jquery – Jobst May 21 '15 at 07:06

2 Answers2

2

You need to escape the [] characters in the name attribute of the selector (or wrap them in quotes) and remove the un-matched apostrophe at the end. Try this:

var selectedPlan = $("input[name=Plan\\[packageId\\]]:checked").val();
alert(selectedPlan);

// alternatively:
// var selectedPlan = $("input[name='Plan[packageId]']:checked").val();

Updated fiddle

Note that you're running your code on load of the page and your HTML has no radio selected by default. I added a checked attribute to one of the radios so you can see it working. Also, your original fiddle did not include jQuery so I added that too. Finally, the element is label, not lable.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
2

You need to escape the CSS meta characters or wrap them in quote for preventing the selector from breaking:

var selectedPlan = $("input[name='Plan[packageId]']:checked").val();

Working Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125