比较输入验证html javascript中的两个输入值?

时间:2013-09-20 19:58:26

标签: javascript html

我想比较两个输入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也会显示警告,你能指出代码中的错误吗?

3 个答案:

答案 0 :(得分:3)

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

if(maxN<min) {

应该是

if(max<min) {

答案 1 :(得分:3)

这里很少有东西

关闭输入元素:

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

答案 2 :(得分:1)

transactionManager
function checknumber(theForm) {   
 if (parseInt(theForm.num2.value) != (parseInt(theForm.num1.value)+1)) 
    { 
    alert('enter the correct year in intermediate');
            return false;
            } 
     return true;
            
}