Using Javascript to compare two input numbers in HTML?

前端 未结 4 2042
没有蜡笔的小新
没有蜡笔的小新 2020-12-07 03:55

I am using Notepad++ to create a simple web page where a user types in two numbers into a text box, and then presses a button. When they press the button something comes up

相关标签:
4条回答
  • 2020-12-07 04:13

    Html is a string, not a value. You need to parse it in someway.

    EDIT:

    The problem seems to be grabbing the values, change it to getElementById and it works fine:

    http://jsfiddle.net/fHtZU/10/

    HTML

    <h1>Assignment 10</h1>
    
    <div id="container">
        <div class="Num">
        <form>
    <label class="label1">Enter Value 1:</label>
    <input type="text" id="First_num" name="First_num" />
    <label class="label1">Enter Value 2:</label>
    <input type="text" id="last_num" name="last_num" />
    <br/>
    <input type="button" id="clickme" value="Which number is greater?" onclick="greaterNum()" />
    </form>
    

    js

    function greaterNum(){
        var value1;
        var value2;
        value1 = document.getElementById("First_num").value;
        value2 = document.getElementById("last_num").value;
        if (value1 > value2){
            alert(value1 - value2);
            document.body.style.background = "orange";
        }
    
    }
    
    0 讨论(0)
  • 2020-12-07 04:22

    Convert to floats.

    value1 = parseFloat(document.First_num.value);
    value2 = parseFloat(document.last_num.value);
    
    0 讨论(0)
  • 2020-12-07 04:32

    Values from inputs are retrieved as strings, you need to convert it to number. Try this:

    value1 = +document.First_num.value;
    value2 = +document.last_num.value;
    

    Also, try to be consistent when naming your input, why caps for one and lowercase for the other?

    0 讨论(0)
  • 2020-12-07 04:36

    You may need to use:

    value1 = document.getElementById("First_num").value;
    

    However, this only works if you assign the elements id attributes:

    <input type="text" id="First_num" name="First_num" value=" " />
    

    Otherwise, use the getElementsByName.

    Hope this helps!!

    0 讨论(0)
提交回复
热议问题