可能是重复问题:
使用jQuery检查输入是否为空
我有一个表单和文本框,当表单按钮被点击时,如何使用JavaScript if else语句确定这些文本框中是否有任何一个为空。
function checking() {
var textBox = $('input:text').value;
if (textBox == "") {
$("#error").show('slow');
}
}
感谢您的提前支持!
可能是重复问题:
使用jQuery检查输入是否为空
我有一个表单和文本框,当表单按钮被点击时,如何使用JavaScript if else语句确定这些文本框中是否有任何一个为空。
function checking() {
var textBox = $('input:text').value;
if (textBox == "") {
$("#error").show('slow');
}
}
使用jQuery选择器选择元素时,您将得到一个jQuery对象,应该使用val()
方法来获取/设置输入元素的值。
还要注意,:text
选择器已被弃用,最好通过修剪文本来移除空格字符。您可以使用$.trim
实用函数。
function checking() {
var textBox = $.trim( $('input[type=text]').val() )
if (textBox == "") {
$("#error").show('slow');
}
}
如果您想使用value
属性,您应该首先将jQuery对象转换为原始DOM对象。您可以使用[index]
或get
方法。
var textBox = $('input[type=text]')[0].value;
如果您有多个输入,应该通过循环处理它们。function checking() {
var empty = 0;
$('input[type=text]').each(function(){
if (this.value == "") {
empty++;
$("#error").show('slow');
}
})
alert(empty + ' empty input(s)')
}
function checking()
{
if(document.getElementById("entry_0").value == "")
{
$("#error").show('slow');
}
if(document.getElementById("entry_1").value == "")
{
$("#error").show('slow');
}
}
想象一下,如果我有20个文本框。这就是为什么我试图调用输入:文本对象本身或“表单输入”以调用所有文本框在一个函数中。谢谢! - ray在使用jquery对象时,不能使用value
属性,而应该使用val()
函数。但是这个函数只会检查选择器返回的第一个文本框。
function checking() {
var textBox = $('input:text').val();
if (textBox == "") {
$("#error").show('slow');
}
}
模糊
事件并在每个文本框失去焦点时进行此验证。
实时演示
$('input:text').blur(function() {
var textBox = $('input:text').val();
if (textBox == "") {
$("#error").show('slow');
}
});
根据与OP的讨论,提交按钮
点击时的验证。
$('#btnSubmit').click(function() {
$("#error").hide();
$('input:text').each(function(){
if( $(this).val().length == 0)
$("#error").show('slow');
});
});
尝试这段代码:
var textBox = $('input:text').val();
if (textBox==""){
$("#error").show('slow');
}