我有表单和文本框,如果单击表单按钮,我将如何使用javascript if else语句确定这些文本框中是否为空。
function checking() {
var textBox = $('input:text').value;
if (textBox == "") {
$("#error").show('slow');
}
}
提前致谢!
答案 0 :(得分:13)
通过使用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)')
}
答案 1 :(得分:5)
您不能将value
与jquery对象使用val()
函数一起使用,但这只会检查选择器返回的第一个文本框。
<强> Live Demo 强>
function checking() {
var textBox = $('input:text').val();
if (textBox == "") {
$("#error").show('slow');
}
}
您可以附加blur
个事件,并在losing focus from each textbox.
<强> Live Demo 强>
$('input:text').blur(function() {
var textBox = $('input:text').val();
if (textBox == "") {
$("#error").show('slow');
}
});
根据与OP
的讨论,submit button
点击验证
<强> Live Demo 强>
$('#btnSubmit').click(function() {
$("#error").hide();
$('input:text').each(function(){
if( $(this).val().length == 0)
$("#error").show('slow');
});
});
答案 2 :(得分:1)
试试这段代码:
var textBox = $('input:text').val();
if (textBox==""){
$("#error").show('slow');
}