Nave Tseva
Nave Tseva

Reputation: 878

Can't get the selected radio button value via JQuery

I have the following HTML code:

<form id="pick-status-form">
<div class='form-group'>
    <div class='radio'><label><input type='radio' name='ststusesList' value='1' class='statuses-list'>1</label></div>
    <div class='radio'><label><input type='radio' name='ststusesList' value='2' class='statuses-list'>2</label></div>
    <div class='radio'><label><input type='radio' name='ststusesList' value='3' class='statuses-list'>3</label></div>
    <div class='radio'><label><input type='radio' name='ststusesList' value='4' class='statuses-list'>4</label></div>
    </div></form>

And these Jquery code:

$("button#submit").click(function () {
      var form = $('#pick-status-form');
      var selectedStatusID = form.find('input[name=ststusesList]:checked').val();
      alert(selectedStatusID);
});

The problem is that the value of selectedStatusID is always undefined.

My question is why and how can I fix it?

HERE is a fiddle: http://jsfiddle.net/b6xFA/

Upvotes: 0

Views: 282

Answers (1)

nkmol
nkmol

Reputation: 8091

Your code just works as intended.

Why does it gives undefined?

This is because the value of a checkbox is only declared when it is checked. None of your checkboxes are checked when running the page for the first time.

See this example were the first checkbox is checked by default:

<input type='radio' name='ststusesList' value='1' class='statuses-list' checked="checked" />

jsFiddle

Upvotes: 2

Related Questions