我有 3 个文本字段,可以将数据添加到表中,但是,即使所有字段为空,我也可以将数据提交到表中,这种形式的验证可以与普通 jQuery 一起使用还是必须与插件一起使用? .
空文本框验证jQuery
答案:
您可以使用 jQuery 完成此操作,而无需使用任何其他插件。这个脚本可以解决问题。请注意,它会遍历您的所有文本字段。我还为用户添加了视觉确认(绿色边框 == OK,红色边框 == 'not OK')。
希望你可以使用它。
$('#yourSubmitButtonId').click(function(){
var isValid = 1;
$('input:text').each(function(){
if($(this).val() == ''){
$(this).css('border','1px solid red');
isValid = 0;
}
else{
$(this).css('border','1px solid green');
}
});
if(isValid == 0){
alert('Please enter content to all text fields');
return false;
}
//if valid then do something
});
“如果任何一个框是空的,我想要一个警报并且不希望调用函数‘AddScore’”
所以,我们开始吧。您只需要找出填充输入的数量是否小于输入的总数。所以,稍微改变你的功能如下:
function AddScore() {
var totalInputs = $('div[data-role="fieldcontain"] input:text').length;
var nonEmptyInputs = $('div[data-role="fieldcontain"] input:text').filter(function(){return $.trim($(this).val()) !== ""}).length;
if (nonEmptyInputs < totalInputs) {
alert ("You've not filled all the boxes");
return; //stop execution
}
//rest of the code
var jqTableBody = $('#myTable tbody');
....
....
您可以明确地检查它们:
或者,如果您想为将来支持可变数量的字段,则可以使用以下方法:
Here's a working example.