0

Why is result undefined?

My code

var radios = document.querySelectorAll('input[type=radio]');
var result = document.querySelector('.result');
var a;

for (var i = 0; i < radios.length; i++) {
  radios[i].addEventListener('change', function() {
    a = this.dataset.number;
  });
}
result.innerHTML = a;
<input type="radio" name="r" data-number="2" value="Radio 1">Radio 1
<input type="radio" name="r" data-number="4" value="Radio 2">Radio 2
<input type="radio" name="r" data-number="8" value="Radio 3">Radio 3

<div class="result">Result</div>

Javascript

var radios = document.querySelectorAll('input[type=radio]');
var result = document.querySelector('.result');
var a;

for (var i = 0; i < radios.length; i++) {
  radios[i].addEventListener('change', function() {
    a = this.dataset.number;
  });
}
result.innerHTML = a;

I will be glad to any help

ivansimonov007
  • 107
  • 1
  • 11
  • Assigning the value of the variable "a" should be where "a" is updated, inside the change callback function. – progysm Aug 12 '18 at 14:43
  • @Jeremy Close match, but OP probably *[needs clarification]* doesn't want to wait until something changed. – user202729 Aug 12 '18 at 14:44
  • var radios = document.querySelectorAll('input[type=radio]'); var result = document.querySelector('.result'); var a; for (var i = 0; i < radios.length; i++) { radios[i].addEventListener('change', function() { a = this.dataset.number; result.innerHTML = a; }); } Hope it will help – Nadeem Ahmad Aug 12 '18 at 14:45
  • @NikxFabrizio No answer in comment. If it's a dupe, it is. If you think it's not a dupe, work to reopen it. – user202729 Aug 12 '18 at 14:46
  • result.innerHTML = this.dataset.number; so works. But how is this value used in another expression? – ivansimonov007 Aug 12 '18 at 14:46
  • @user202729 we're not in an examination room, if we can help someone with accurate answer and save the person some time/effort then it's worth doing. stackoverflow is a place to provide answers to those who needs them. – Nadeem Ahmad Aug 12 '18 at 14:54
  • @NikxFabrizio {this assumes the question is a real duplicate. not this case} The OP can check the duplicate target and find better answers. If you have a good answer, you should post there, as it can help both OP and future visitors, not here. – user202729 Aug 12 '18 at 14:57
  • example https://jsfiddle.net/qrL8dxbs/ - why at the first choice - the necessary value is not displayed? – ivansimonov007 Aug 12 '18 at 15:18

0 Answers0