charsi charsi - 3 months ago 27
Javascript Question

Getting value from mdl radio button

In the following code why doesn't the radio report the correct value when checked via its variable name?

var $myRadio = $('input[type=radio][name=options]:checked');

$('#button').click(() => {
// this works
console.log($('input[type=radio][name=options]:checked').val());
// this doesn't :(
console.log($myRadio.val());
});


https://jsfiddle.net/charsi/p4beztwx/13/

I am using mdl radio buttons so that could be causing it. I have also tried getting the value with
$myRadio[0].MaterialRadio.value
but that doesn't work either.

Answer

The reason for getting incorrect values when checked via its variable name is because you are setting $myRadio before the click event. $myRadio is set on document ready (before click event) and it gets the value of the checked radio option which at this moment is always 1.

Moving $myRadio inside a click handler should work. Why? Because now it gets the value of the radio (checked) as soon as the click function is called which is actually what you need.

$('#button').click(() => {
  var $myRadio = $('[id^="option"]:checked');
  // neither of these work
  alert($('input[type=radio][name=options]:checked').val());
  alert($myRadio.val());

});

fiddle here