"undefined" Error with onchange event

I want to do this when I press a button, it will print a different number, depending on which button I click. I want the buttons to look the same . This is what I have:

<div id="radiobuttons" class="container" name="buttons" align=center onchange="myFunction">

    <h2>I Want my Building to be Made of:</h2>

  <ul>
  <li>
    <input type="radio" id="brick-option" name="material" value="1">
    <label for="brick-option">Bricks</label>

    <div class="check"></div>
  </li>

  <li>
    <input type="radio" id="wood-option" name="material" value="3">
    <label for="wood-option">Wood</label>

    <div class="check"><div class="inside"></div></div>
  </li>

  <li>
    <input type="radio" id="stone-option" name="material" value="2">
    <label for="stone-option">Stone</label>

    <div class="check"><div class="inside"></div></div>
  </li>
</ul>
</div>

<p id="paragraph" align="center">0</p>

<script>

function myFunction() {
    var x = document.getElementById("radiobuttons").value;
    document.getElementById("paragraph").innerHTML = x;
}

</script>

Although, when I click the button, it says undefined. What does this mean and how can I fix it?

+4
source share
2 answers

changean event is not raised for an element div. You will have to attach it to the switches, for which they will obviously be called.

It is also recommended to avoid inline event handlers and attach handlers in JS to avoid pollution HTML

HTML

<div id="radiobuttons" class="container" name="buttons" align=center>

  <h2>I Want my Building to be Made of:</h2>

  <ul>
    <li>
      <input type="radio" id="brick-option" name="material" value="1">
      <label for="brick-option">Bricks</label>

      <div class="check"></div>
    </li>

    <li>
      <input type="radio" id="wood-option" name="material" value="3">
      <label for="wood-option">Wood</label>

      <div class="check">
        <div class="inside"></div>
      </div>
    </li>

    <li>
      <input type="radio" id="stone-option" name="material" value="2">
      <label for="stone-option">Stone</label>

      <div class="check">
        <div class="inside"></div>
      </div>
    </li>
  </ul>
</div>

<p id="paragraph" align="center">0</p>

Js

var radioButtons = document.querySelectorAll('input[type=radio]');

for (var i = 0; i < radioButtons.length; i++) {
  radioButtons[i].addEventListener('change', function() {
    if (this.checked) {
      document.getElementById("paragraph").innerHTML = this.value;
    }
  });
}

Check feed

+1

value on radiobuttons, <div>, , 'undefined'.

, myFunction inline onClick .

+1

Source: https://habr.com/ru/post/1664225/


All Articles