JQuery: How to get selected radio button value? JQuery: How to get selected radio button value? jquery jquery

JQuery: How to get selected radio button value?


$('input[name=myradiobutton]:radio:checked') will get you the selected radio button$('input[name=myradiobutton]:radio:not(:checked)') will get you the unselected radio buttons

Using this you can do this

$('input[name=myradiobutton]:radio:not(:checked)').val("0");

Update: After reading your Update I think I understandYou will want to do something like this

var myRadioValue;function radioValue(jqRadioButton){  if (jqRadioButton.length) {    myRadioValue = jqRadioButton.val();  }  else {    myRadioValue = 0;  }}$(document).ready(function () {  $('input[name=myradiobutton]:radio').click(function () {   //Hook the click event for selected elements    radioValue($('input[name=myradiobutton]:radio:checked'));  });  radioValue($('input[name=myradiobutton]:radio:checked')); //check for value on page load});


Use the :checked selector to determine if a value is selected:

function getRadioValue () {    if( $('input[name=myradiobutton]:radio:checked').length > 0 ) {        return $('input[name=myradiobutton]:radio:checked').val();    }    else {        return 0;    }}

Update you can call the function above at any time to get the selected value of the radio buttons. You can hook into it on load and then whenever the value changes with the following events:

$(document).ready( function() {    // Value when you load the page for the first time    // Will return 0 the first time it's called    var radio_button_value = getRadioValue();    $('input[name=myradiobutton]:radio').click( function() {        // Will get the newly selected value        radio_button_value = getRadioValue();    });}


It will start as soon as the page loads.You can keep it under some events like button click

$("#btn").click(function() { var val= $('input[type="radio"]:checked').val();});