0

我想比较两个输入 minimumN 和 maximumN,并在不满足逻辑时显示警报,我有以下代码:

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.");
    }
}

但这不起作用,即使 minN 小于 maxN 也会显示警报,您能指出我的代码中的错误吗?

4

3 回答 3

4

这里的东西很少

关闭输入元素:

if(maxN<min) {

应该

if(max<min) {

最后,您不是在比较整数而是在比较字符串,所以..

5<9
555<9
1000<20

它的“字母”

您需要将它们解析为 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 );
       } 
  }
于 2013-09-20T20:35:15.610 回答
3

在第二个函数MaximumNValidate()中,你有这行代码

if(maxN<min) {

应该是

if(max<min) {
于 2013-09-20T20:02:29.193 回答
1

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> 

于 2019-11-20T14:48:49.053 回答