0

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.

EDIT: This was a poorly worded question and didn't really have anythng to do with mdl. What I really wanted was the ability to set the DOM variable for my radio button somewhere else without having to select it by name again to check the value.

charsi
  • 2,917
  • 22
  • 40

2 Answers2

1

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

bipen
  • 36,319
  • 9
  • 49
  • 62
  • hmm, thanks for the answer. makes sense. I was somehow under the impression this is not how it works for standard radio buttons. I was wrong. – charsi Aug 17 '16 at 16:37
  • Any way of assigning the variable somwhere else? – charsi Aug 17 '16 at 16:38
  • No, if you want to check the variable inside a click or change event. And why would you want to assign variable somewhere else when you need it here . This is completely fine. – bipen Aug 17 '16 at 16:41
  • I like to declare my DOM variables once so they remain separate from the rest of the code. – charsi Aug 17 '16 at 16:43
  • Ya make sense and its a good practice but not in such case where your variable depends on some event. :) – bipen Aug 17 '16 at 16:46
  • 1
    Found what I was looking for - http://stackoverflow.com/questions/31970919/get-the-value-of-checked-radio-button-without-re-selecting-the-buttons – charsi Aug 17 '16 at 16:46
1

For anyone else running into the same issue. Not wanting to call the radio button name when checking for its value, you can use filter -

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

$('#button').click(() => {
  console.log($myRadio.filter(':checked').val());
}
charsi
  • 2,917
  • 22
  • 40