在Javascript中检查文本框是否为空 [英] Checking if a textbox is empty in Javascript

查看:107
本文介绍了在Javascript中检查文本框是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,如果文本框留空,它应该引发 alert 消息:

 函数a(id)
{
var n = document.getElementById(id).value;
if(n.length< 1)
{
window.alert(Field is blank);
返回false;
}
}

我得到的错误是字段是第一次没有得到验证 onChange 。但是,当文本框中填充了一些数据并被删除时,现在 OnChange 被触发,并且显示 alert 消息。如何修复这个bug?

解决方案

onchange 文本框的值与之前的值相比发生了变化,所以第一次它不起作用,因为状态没有改变。



所以它是更好地使用 onblur 事件或提交表单。

 函数checkTextField(field){document.getElementById(error)。innerText =(field.value ===)? 领域是空的。 :Field is filled。;}  

< input type =textonblur =checkTextField(this); />< p id =error>< / p>

$ b

(or old live demo。)


This is my code which was supposed to raise an alert message if the textbox is left empty:

function a(id)
{
    var n=document.getElementById(id).value;
    if (n.length < 1)
    {
        window.alert("Field is blank");
        return false;
    }
}

The bug I'm getting is that the field is not getting verified onChange the first time. But when the text box is filled with some data and erased, now the OnChange fires, and the alert message is displayed. How can I fix this bug?

解决方案

onchange will work only if the value of the textbox changed compared to the value it had before, so for the first time it won't work because the state didn't change.

So it is better to use onblur event or on submitting the form.

function checkTextField(field) {
  document.getElementById("error").innerText =
    (field.value === "") ? "Field is empty." : "Field is filled.";
}

<input type="text" onblur="checkTextField(this);" />
<p id="error"></p>

(Or old live demo.)

这篇关于在Javascript中检查文本框是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆