如何在javascript中检查我的任何文本框是否为空

问题描述:


可能重复:

使用jQuery检查输入是否为空

我有表单和文本框,一旦单击表单按钮,如何使用javascript if else语句确定这些文本框中是否为空。

I have form and textboxes, how will I determine if any of these textboxes is empty using javascript if else statement once a form button is clicked.

function checking() {
    var textBox = $('input:text').value;
    if (textBox == "") {
        $("#error").show('slow');
    }
}

提前致谢!

通过使用jQuery选择器来选择元素,你有一个jQuery对象,你应该使用 val()获取/设置输入元素值的方法。

By using jQuery selectors for selecting the elements, you have a jQuery object and you should use val() method for getting/setting value of input elements.

另请注意:text 选择器已弃用并且最好修剪用于删除空白字符的文本。你可以使用 $。trim 效用函数。

Also note that :text selector is deprecated and it would be better to trim the text for removing whitespace characters. you can use $.trim utility function.

function checking() {
    var textBox =  $.trim( $('input[type=text]').val() )
    if (textBox == "") {
        $("#error").show('slow');
    }
}

如果你想使用 value 属性您应该首先将jQuery对象转换为原始DOM对象。您可以使用 [index] 获取方法。

If you want to use value property you should first convert the jQuery object to a raw DOM object. You can use [index] or get method.

 var textBox = $('input[type=text]')[0].value;

如果你有多个输入,你应该遍历它们。

If you have multiple inputs you should loop through them.

function checking() {
    var empty = 0;
    $('input[type=text]').each(function(){
       if (this.value == "") {
           empty++;
           $("#error").show('slow');
       } 
    })
   alert(empty + ' empty input(s)')
}