2017-02-28 58 views
0

我在输入时验证用户输入有一些麻烦。如何在用户输入值时验证文本框使用javascript

例如:有效范围为600-800和用户正在尝试输入700

When textbox is empty: show nothing 

When textbox is 7: show red 

When textbox is 70: show red 

When textbox is 700:show nothing 

我希望我能在JS做到这一点,任何人都可以帮我吗?

+0

你到目前为止尝试过什么? –

+0

我可以在用户完成输入时验证输入,但在此过程中我无法验证输入。 – SwordW

+0

说实话,我不知道如何让它发生 – SwordW

回答

0

下面是另一个例子,看起来像你的问题已经在我写这篇文章时回答。

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
    <meta charset = "utf-8"> 
    <style> 
     .red { 
      background-color: red; 
     } 
    </style> 
    </head> 
    <body> 
     <form id="myForm"> 
     <input type="text" id="validate" class=""/> 
     </form> 
    <script> 
    function pressHandler(e) { 
     console.log(this.value); 
     if (parseInt(this.value) <= 700) { 
      this.className = "red"; 
     } else { 
      this.className = ""; 
     } 
    } 

    document.getElementById("validate").addEventListener("keyup",pressHandler); 
    </script> 

    </body> 
</html> 
0

听起来像你正在使用onchange事件。

如果您尝试onkeypress它应该做你以后的事情。

1

这里一看就是一个例子:

<input type="text" id="myTextBox" onKeyUp="checkInput()" /> 
<script> 
var myTextBox = document.getElementById('myTextBox'); 
function checkInput() { 
    var value = myTextBox.value; 
    if (!value || isNaN(value) || parseInt(value, 10) < 700 || parseInt(value, 10) > 800) { 
    myTextBox.style.backgroundColor = 'red'; 
    } else { 
    myTextBox.style.backgroundColor = 'green'; 
    } 
} 
</script>