Reputation: 3885
I'm pretty much a total jquery noob I'm afraid! I'm sure this is a very simple thing but I can't seem to work it out.
I'm trying to get the value of a dynamic, selected radio button.
HTML...
<div id="holder" class="">
<table id="qual-holder" class="table table-striped qual-table">
<thead>
<tr>
<th>Sector</th>
<th>Qualification Title</th>
<th>Cost</th>
<th>Confirm</th>
</tr>
</thead>
<tr class="sector_qual">
<td>OM207</td>
<td>Diploma in Children and Young People's Workforce Level 3</td>
<td>0</td>
<td>
<input name="qualification" id="28" type="radio" value="28" class="">
</td>
</tr>
<tr class="sector_qual">
<td>OM207</td>
<td>Diploma in Children and Young People's Workforce</td>
<td>0</td>
<td>
<input name="qualification" id="29" type="radio" value="29" class="">
</td>
</tr>
<tbody id="sector_quals"></tbody>
</table>
<div class="control-group spacing-top">
<label for="loan_value" class="control-label required">Amount to Borrow</label>
<div class="controls">
<div class="input-prepend"> <span class="add-on"><i class="icon-gbp"></i></span>
<input class="input-small" placeholder="" name="loan_value" type="text" value="" id="loan_value">
</div>
</div>
</div>
And my (rubbish) jQuery...
function updateAmount() {
var selectedValue = "";
var selected = $("input:radio[name='qualification']:checked");
if (selected.length > 0) {
selectedValue = selected.val();
alert('The radio button has been selected and the value is.' + selectedValue);
}
}
updateAmount();
Can someone please tell me what I'm doing wrong?
Thanks
Upvotes: 0
Views: 6148
Reputation: 11
Try this:
Give a class to all radio buttons
. e.g. radio.
$(".radio").change(function(){
var selected_value = $(this).val();
alert('The radio button has been selected and the value is ' + selected_value);
});
Upvotes: 0
Reputation: 42736
You are calling updateAmount too early, bind a click event and have the callback as updateAmount, or the change
event as roasted mentions, as the event will be triggered only when the actual selection has changed instead of just being clicked on.
jQuery(document).on("click",'input:radio[name=qualification]',updateAmount);
the .on
function makes it so current radio buttons and any new radio buttons' click event gets fired
Upvotes: 6
Reputation: 48415
Your code is actually fine. The problem is where you are calling updateAmount()
. If you want this to be called when the user select an option, then call it from within the change()
event. Like so:
$("input:radio[name='qualification']").change(function () {
updateAmount();
});
Upvotes: 2