charsi charsi - 1 year ago 97
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
// this doesn't :(

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

Answer Source

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


fiddle here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download