Reputation: 473
I have a variable called category
that must change its value according to the selected radio button. The problem is that I do not get that at the click of a radio button or another, the value will change instantly.
This is the code I have:
<form>
<input type="radio" name="category" value="doctor" /> Doctor
<input type="radio" name="category" value="police" checked /> Policia
</form>
var category = $('[name="category"]:checked').val();
I need you to automatically change the value of the variable category
when you click the radio buttons.
Upvotes: 14
Views: 68384
Reputation: 11
You shouldn't give the same ID for more than one element, you should use class instead like this :
<form>
Option 1<input type="radio" name="opt" class="radio" value="Option 1">
Option 2<input type="radio" name="opt" class="radio" value="Option 2">
</form>
instead of :
<form>
Option 1<input type="radio" name="opt" id="radio" value="Option 1">
Option 2<input type="radio" name="opt" id="radio" value="Option 2">
</form>
and your code still the same and it should work fine :)
Upvotes: 1
Reputation: 131
var category;
$(':radio[name="category"]').change(function() {
category=this.value;
});
And this is a jsfiddle.net demo.
Upvotes: 2
Reputation: 298046
Attach an event handler to the change
event:
$(':radio[name="category"]').change(function() {
var category = $(this).filter(':checked').val();
});
Upvotes: 45
Reputation: 10258
You need to change the value of category every time a user changes the selected radio button. Therefore you will need an event to trigger when the user clicks on a radio. You can check out the FIDDLE
var category = null;
$("input[name='category']").click(function() {
category = this.value;
});
Upvotes: 19
Reputation: 2764
utilize the .change() in order to capture the change event for a radio button.
Upvotes: 0
Reputation: 69905
Instead of using category
variable use $('[name="category"]:checked').val()
wherever you want the value of the checked radio button. Otherwise you can make use of change
or click
event to set the checked
radio buttons value into category
variable.
Upvotes: 0
Reputation: 6335
I think you need simply something like this:
var category;
$('radio[name="category"]').click(function(){
category=this.value;
});
Upvotes: 1