1

I wrote a very simple JavaScript function to take a numeric input and show it on screen as the innerHTML of a paragraph element. The function was named 'multiple' (see code below). It did not work.

However, changing the name of the function to 'myMultiple' enabled the script to work. I cannot see 'multiple' on the list of reserved JavaScript words - is something else causing this error?

<body>

<p>Write something in the text field to trigger a function.</p>

<input type="text" id="funcnTest" oninput="multiple()">
<p id="myOutput"></p>

<script>
function multiple() {
    var myInputVal = document.getElementById("funcnTest").value;
    document.getElementById("myOutput").innerHTML = "The value: " + myInputVal;
}
</script>

</body>
AndyG
  • 9
  • 4
  • No it is not a reserved keyword, I guess it was just a typo? – Jonas Wilms Jan 13 '19 at 21:11
  • 4
    Scope issue. You're hitting a *different* `multiple` in the DOM. Nothing to do with JS reserved words. Intrinsic event attributes are awful for this. Use `addEventListener` instead. – Quentin Jan 13 '19 at 21:13
  • Please, define what you mean by "it did not work". Did you get a syntax error saying something about an unexpected keyword or an illegal error? If you didn't get a syntax error, then the problem is obviously not with the syntac. – Jörg W Mittag Jan 13 '19 at 21:22
  • it works only if i change oninput="multiple()" with oninput="window.multiple()". Hence, it seems a scope issue... – gaetanoM Jan 13 '19 at 21:24
  • 1
    TL;DR: `multiple` is a property of [`HTMLInputElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) and has precedence. – xehpuk Jan 13 '19 at 21:37
  • Thanks for the answers, everyone. For additional background:This was definitely not a typo. – AndyG Jan 15 '19 at 11:46
  • The FireFox JavaScript console error was TypeError: multiple is not a function. I gave the input field a name (myInput) and then as per Quentin's suggestion used addEventListener instead of oninput to call the multiple function: 'document.getElementsByName("myInput")[0].addEventListener('input', multiple);'. This time it worked: no errors. – AndyG Jan 15 '19 at 12:05

0 Answers0