Conner McClellan
Conner McClellan

Reputation: 27

HTML input as a JavaScript variable

I'm hoping this isn't a huge hassle. I'm working on a project to practice my HTML and JavaScript. I have a text box that takes numbers, and I want a button to take that number and do some calculations with it. However, I can't seem to figure out how to turn the HTML input into a variable the JavaScript will take. Here is my HTML:

<!doctype html>
<!-- project10.html -->

<html>
    <head>
        Hello! <br>
        This generator takes an odd number and prints out all odd numbers below it down to 0. <br>
        Enter the number you want to calculate, between 1 and 10, and then click the text below. <br>
    </head>
    <body>
    Enter your number: <input type="number" id="numberBox" size=12 value="9">
        <title>Testing Function</title>
        <script type="text/javascript" src="test.js"></script>
        <p id="demo" onclick="myFunction(9)">Click this to show numbers.</p>
    </body>
</html>

Here is the test.js file, located in the same folder:

function myFunction(b2){
    b1 = b2 % 2;
    b2 = b2 - 1 + b1;
    if (b2 < 1) {
        document.getElementById("demo").innerHTML = "Number too low!";
    } 
    else if (b2 > 10) {
        document.getElementById("demo").innerHTML = "Number too high!";
    } 
    else {
        document.getElementById("demo").innerHTML ="";
        for (i=b2;i>0;i--){
            document.getElementById("demo").innerHTML += i +'<br>';
            i--;
        }
    }
}

This will be the last help I need for quite awhile. I'm probably just overlooking something and it burns.

Upvotes: 0

Views: 55

Answers (2)

Redemption Okoro
Redemption Okoro

Reputation: 379

You passed a value to the function during call, you were suppose to get the value in the function

Try this in your HTML file <p id="demo" onclick="myFunction()">Click this to show numbers.</p>

Notice that I removed the 9 in myFunction()

Upvotes: 0

Mick
Mick

Reputation: 796

<!doctype html>
<!-- project10.html -->

<html>
    <head>
        Hello! <br>
        This generator takes an odd number and prints out all odd numbers below it down to 0. <br>
        Enter the number you want to calculate, between 1 and 10, and then click the text below. <br>
    </head>
    <body>
    Enter your number: <input type="number" id="numberBox" size=12 value="9">
        <title>Testing Function</title>
        <script type="text/javascript" src="test.js"></script>
        <button id="demo" onclick="myFunction()">Click this to show numbers.</button>
    </body>
</html>

<script>
function myFunction() {
    let input = document.getElementById("numberBox").value;
    console.log(input);
}
<script>

Upvotes: 1

Related Questions