Reputation: 202
I am having an issue I am not able to resolve despite through research and effort. So I am posting it here. I have two input radio button elements with the same name
, which represent Business Bank Account Service
being used or not:
<input type="radio" name="bank_account_service" value="no" checked='checked'>No
<input type="radio" name="bank_account_service" value="yes">Yes
Now I also have the following JQuery function which should alert the value of this radio selection:
var bank=$('input[name=bank_account_service]:checked').val();
$(document).click(function(){alert(bank);});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Business Bank Account<br/>
<br/><input type="radio" name="bank_account_service" value="no" checked='checked'>No
<br/><input type="radio" name="bank_account_service" value="yes">Yes<br/><br/>
I want to alert yes when the radio button for Yes
is checked. Can anyone guide me as to what am I missing or doing wrong please?
Upvotes: 1
Views: 1223
Reputation: 3
<form>
<div>
<input type="radio" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="radio" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="radio" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
<script>
$( "input" ).on( "click", function() {
$( "#log" ).html( $( "input[name='fruit']:checked" ).val() + " is checked!" );
});
</script>
Try something like this !!!
Upvotes: 0
Reputation: 453
You might be looking for this:
$('input[name=bank_account_service]').click(function () {
alert($('input[name=bank_account_service]:checked', '#yourForm').val())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Business Bank Account<br/>
<form id="yourForm">
<br/><input type="radio" name="bank_account_service" value="no" checked='checked'>No
<br/><input type="radio" name="bank_account_service" value="yes">Yes<br/><br/>
</form>
Upvotes: 2
Reputation: 2137
Looks like you've got some of your jquery backwards.
Try this:
//all click events go in here
$(document).ready(function(){
//click event on all of these bank inputs
$('input[name=bank_account_service]').click(function(){
//check to see if this is the yes option
if ($(this).val()=='yes') {
//do something
}
});
});
You might also want to consider putting unique IDs for each of your radio buttons. So if you could change your HTML to this:
<input type="radio" name="bank_account_service" value="no" id='bank_no'>No
<input type="radio" name="bank_account_service" value="yes" id='bank_yes'>Yes
Then you could make your jquery:
$(document).ready(function(){
//click event on only the yes input
$('#bank_yes').click(function(){
//do something
});
});
Upvotes: 0