0

I got a problem, I want to add onchange javascript on the selection tag. It is working if the selection tag puts without the form tag, but after I put the selection tag inside the form tag it's stop working,

If I put the selection tag without the form tag it would be okay but when I put the selection tag inside the form tag it's not working anymore

<form>
  <select id="selection1" onchange="selection1();">
    <option value="1.1">1.1</option>
    <option value="1.2">1.2</option>
    <option value="1.3">1.3</option>
  </select>
  <input type="text" id="selectionval" />
</form>
<script type="text/javascript">
  function selection1() {
    var id = document.getElementById("selection1");
    var displayedText = id.options[id.selectedIndex].text;
    document.getElementById("selectionval").value = displayedText;
  }
</script>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Change the name of the function or better: use event listener: `window.addEventListener("DOMContentLoaded", function() { const select = document.getElementById("selection1"); select.addEventListener("change", function() { const displayedText = this.options[this.selectedIndex].text; document.getElementById("selectionval").value = displayedText; }); });` – mplungjan Apr 03 '22 at 05:42
  • Since `selection1` is the ID of an element, it becomes a (proxified) property on the global object (`globalThis` or `window`) due to legacy behavior. Using 1990s `onchange` attributes makes this property take precedence over the function. Always [use `addEventListener`](//developer.mozilla.org/en/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. – Sebastian Simon Apr 03 '22 at 05:43

0 Answers0