我正处于构建网站的最后阶段,还剩下一项关键任务:设置一些表单验证以阻止用户提交空白搜索。
我知道以下帖子,但发现不清楚如何让它工作,以及如何将其用于下拉列表 ( jQuery Validate - require at least one field in a group to be filled )
我将不胜感激关于我如何做到这一点的任何想法,或任何可能有帮助的指南指示?
最佳答案
这是一个适用于所有表单字段类型的函数:text
、select
、radio
、checkbox
、textarea
、file
和 HTML5 输入类型,如 email
。此函数所做的唯一假设是所有 select
元素都有一个带有 value=""
option
/**
* 1) gather all checkboxes and radio buttons
* 2) gather all inputs that are not checkboxes or radios, and are not buttons (submit/button/reset)
* 3) get only those checkboxes and radio buttons that are checked
* 4) get only those field elements that have a value (spaces get trimmed)
* 5) if the length of both resulting collections is zero, nothing has been filled out
*/
function checkFields(form) {
var checks_radios = form.find(':checkbox, :radio'),
inputs = form.find(':input').not(checks_radios).not('[type="submit"],[type="button"],[type="reset"]'),
checked = checks_radios.filter(':checked'),
filled = inputs.filter(function(){
return $.trim($(this).val()).length > 0;
});
if(checked.length + filled.length === 0) {
return false;
}
return true;
}
$(function(){
$('#myForm').on('submit',function(){
var oneFilled = checkFields($(this));
// oneFilled === true if at least one field has a value
});
});
这是一个演示:
关于javascript - 如何检查表单是否至少填写了一个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12077311/