Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery change value from radio button

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.

like image 417
Nacho Sarmiento Avatar asked Jan 25 '12 21:01

Nacho Sarmiento


People also ask

How to set the value of radio button in jQuery?

$('input:radio[name=cols]'+" #"+newcol). attr('checked',true);

How to make a radio button checked in jQuery?

We can check the status of a radio button by using the :checked jQuery selector together with the jQuery function is . For example: $('#el').is(':checked') . It is exactly the same method we use to check when a checkbox is checked using jQuery.


1 Answers

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;
});
like image 64
Jose Vega Avatar answered Sep 24 '22 12:09

Jose Vega