简体   繁体   中英

compare two input values in input validation html javascript?

I want to compare two inputs minimumN and maximumN, and display an alert if the logic is not satisfied, I have the following code:

HTML:

<table>
    <tr>
        <th>Minimum N</th>
        <td>
            <input id="minN" onkeyup="MinimumNValidate()" type="text" maxlength="50">
        </td>
        <th>Maximum N</th>
        <td>
            <input id="maxN" onkeyup="MaximumNValidate()" type="text" maxlength="50">
        </td>
    </tr>
</table>

Javascript:

function MinimumNValidate() {
    var min = document.getElementById("minN").value;
    var max = document.getElementById("maxN").value;
    if (min > max) {
        alert("Minimum value must be lesser than maximum value.");
    }
}

function MaximumNValidate() {
    var min = document.getElementById("minN").value;
    var max = document.getElementById("maxN").value;
    if (max < min) {
        alert("Maximum value must be greater than minimum value.");
    }
}

but this is not working, and the alert is being displayed even when the minN is less than maxN, can you point out the mistake in my code ?

Few things here

close the input elements:

if(maxN<min) {

Should be

if(max<min) {

Finally, you are not comparing integers but strings so..

5<9
555<9
1000<20

Its "alphabetic"

You need to parse them to int.

parseInt(max) and parseInt(min)

...

function MinimumNValidate(){
       var min = parseInt(document.getElementById("minN").value);
       var max = parseInt(document.getElementById("maxN").value);
       if(min > max) {
           alert("Minimum value must be lesser than maximum value. " + min + " > " + max );
       } 
 }    

    function MaximumNValidate(){
       var min = parseInt(document.getElementById("minN").value);
       var max = parseInt(document.getElementById("maxN").value);
       if(max<min) {
           alert("Maximum value must be greater than minimum value."  + min + " > " + max );
       } 
  }

In the second function MaximumNValidate(), you have the line of code

if(maxN<min) {

which should be

if(max<min) {

 function checknumber(theForm) { if (parseInt(theForm.num2.value) != (parseInt(theForm.num1.value)+1)) { alert('enter the correct year in intermediate'); return false; } return true; }
 <!doctype html> <head> </head> <body> <form action="../" onsubmit="return checknumber(this);"> <label> tenth graduation </label> <input type="number" name="num1" autocomplete="off"><br> <br> <label> Intermediate </label> <input type="number" name="num2" autocomplete="off"> <input type="SUBMIT" value="year validation"> </form>

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