Javascript 如何在javascript中检查我的任何文本框是否为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12437339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if the any of my textbox is empty or not in javascript
提问by ray
Possible Duplicate:
Check if inputs are empty using jQuery
可能的重复:
使用 jQuery 检查输入是否为空
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.
我有表单和文本框,一旦单击表单按钮,我将如何使用 javascript if else 语句确定这些文本框中的任何一个是否为空。
function checking() {
var textBox = $('input:text').value;
if (textBox == "") {
$("#error").show('slow');
}
}
Thanks in advance!
提前致谢!
回答by undefined
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.
通过使用 jQuery 选择器来选择元素,你有一个 jQuery 对象,你应该使用val()
方法来获取/设置输入元素的值。
Also note that :text
selector is deprecatedand it would be better to trim the text for removing whitespace characters. you can use $.trim
utility function.
另请注意,不推荐使用:text
选择器,最好修剪文本以删除空格字符。你可以使用效用函数。$.trim
function checking() {
var textBox = $.trim( $('input[type=text]').val() )
if (textBox == "") {
$("#error").show('slow');
}
}
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.
如果您想使用value
属性,您应该首先将 jQuery 对象转换为原始 DOM 对象。您可以使用[index]
或get
方法。
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)')
}
回答by Adil
You can not use value
with jquery object use val()
function, But this will check only the first textbox returned by the selector.
您不能使用value
jquery 对象使用val()
函数,但这只会检查选择器返回的第一个文本框。
function checking() {
var textBox = $('input:text').val();
if (textBox == "") {
$("#error").show('slow');
}
}
You can attach blur
event and do this validation on losing focus from each textbox.
您可以附加blur
事件并在losing focus from each textbox.
$('input:text').blur(function() {
var textBox = $('input:text').val();
if (textBox == "") {
$("#error").show('slow');
}
});
Validation on submit button
click according to discussion with OP
submit button
根据与 OP 的讨论进行点击验证
? 现场演示
$('#btnSubmit').click(function() {
$("#error").hide();
$('input:text').each(function(){
if( $(this).val().length == 0)
$("#error").show('slow');
});
});
回答by Alessandro Minoccheri
Try this code:
试试这个代码:
var textBox = $('input:text').val();
if (textBox==""){
$("#error").show('slow');
}