简体   繁体   中英

How to call a function from JavaScript in HTML using button?

I am building a simple interpolation and extrapolation element for my website, the user sees a form which he fills in with numerical values and the evaluation is done in my script. Here is the area where the error emanates, if necessary I can share the full code. #JavaScrit function:

function Evaluate(){
if (xp > x0 && xp < x1) {
    console.log(Interp(x0, y0, x1, y1, xp))
} else if (xp > x0 && xp > x1) {
    console.log(Xtrap(x0, y0, x1, y1, xp))
}

#HTML button in form:

<button type="button" id="button" onclick="Evaluate()">Evaluate</button>

#Error from browser console viewer (line 27 is the button):

Uncaught ReferenceError: Evaluate is not defined
    at HTMLButtonElement.onclick (index.html:27)

The reason for the error may be that the function has not yet been initialized, but pressing the button tries to call this function. Your code works for me without errors in the console, I have written in the conditions while the stubs are true and false. To be able to give an answer, you need to see your code in more detail. Your example function is also missing the closing curly brace }

<body>
    <script>
        function Evaluate() {
            if (true) {
                console.log("Interp(x0, y0, x1, y1, xp)");
            } else if (false) {
                console.log("Xtrap(x0, y0, x1, y1, xp)");
            }
        }
    </script>
    <button type="button" id="button" onclick= Evaluate()> Evaluate </button>
</body>

you have made a small mistake you have not end your function:

function Evalute() {
  if (xp > x0 && xp < x1) {
    console.log(Interp(x0, y0, x1, y1, xp))
  } else if (xp > x0 && xp > x1) {
    console.log(Xtrap(x0, y0, x1, y1, xp))
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM