警报输入表格

时间:2015-11-10 05:47:05

标签: javascript forms jsp

我想根据数据类型

对表单输入caharcter发出警报

当我键入错误的输入时,警报显示如下 enter image description here

<head>
<script type="text/javascript">
    function check_field(id) {
        var field = document.getElementById(id);
        var d = document.getElementById('plus');
        if (isNaN(field.value)) {
            d.innerHTML += "Is not number";
        }
    }
</script>
</head>
<body>
<form>
    <input type="text" id="t_field" onchange="check_field('t_field');"/><b id='plus'></b><br>
    <input type="text"/>
</form>
</body>

当我尝试删除输入字符时仍会显示警报,我希望警报更改为另一个警报,否则它会从屏幕上消失。

上面的问题已经解决但是又出现了一个问题

loop

你了解我的意思吗?

3 个答案:

答案 0 :(得分:2)

添加else块以处理它是正确的输入。

if (isNaN(field.value)) 
{
  d.innerHTML = "Is not number";
}
else
{
  d.innerHTML = "";
}

&#13;
&#13;
<head>
<script type="text/javascript">
    function check_field(id) {
        var field = document.getElementById(id);
        var d = document.getElementById('plus');
        if (isNaN(field.value)) {
            d.innerHTML = "Is not number";
        }
      else
        {
            d.innerHTML = "";
          }
    }
</script>
</head>
<body>
<form>
    <input type="text" id="t_field" onchange="check_field('t_field');"/><b id='plus'></b>
</form>
</body>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

&#13;
&#13;
function check_field(id) {
        var field = document.getElementById(id);
        var d = document.getElementById('plus');
        if (isNaN(field.value)) {
            d.innerHTML = "Is not number";
        } else {
          d.innerHTML = "";
        }
    }
&#13;
<head>
</head>
<body>
<form>
    <input type="text" id="t_field" onkeyup="check_field('t_field');"/><b id='plus'></b><br>
    <input type="text"/>
</form>
</body>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

请尽量减少您的代码,如下所示

 <head>
        <script type="text/javascript">
            function check_field(id) {
                var d = document.getElementById('plus');
                if (isNaN(id.value)) {
                    d.innerHTML = "Is not number";
                }
               else
               {
                  d.innerHTML = "";
               }
            }
        </script>
        </head>
        <body>
        <form>
            <input type="text" id="t_field" onchange="check_field(this);"/><b id='plus'></b><br>
            <input type="text"/>
        </form>
        </body>