![](/img/trans.png)
[英]Either Can Not submit(); form in jQuery, or can not check if input fields are filled out
[英]Check if input fields are filled out in a form
我有一個表單myForm
,我想檢查在發送表單之前是否填寫了特定的輸入字段。 我是JavaScript的新手,所以我真的不知道我做錯了什么。 歡迎任何幫助。
function validateForm() {
var validate = true;
var alert_string = "";
var children = $("#myForm").children("input");
console.log(children.size());
for(var i = 0; i < children.length ; i++){
if(children[i].attr(id).substring(0,8) != "ABC_FLAT"){
if(children[i].attr(id) == null || children[i].attr(id) == ""){
validate = false;
alert_string = alert_string.concat(childrern[i].attr(id)).concat(", ");
}
}
}
alert_string = alert_string.concat("must be filled out !");
if(validate == false){
alert(alert_string);
return false;
}
return true;
}
children[i].attr(id) == "" // wrong
你不必檢查他們的id
是否為null,你必須檢查他們的值是否為空:)
if(children[i].value == "")
由於您已經在使用jQuery,因此可以在很大程度上簡化該代碼。 例如,可以使用簡單的“所有字段填充”檢查
var flag=0;
$('#myForm').each(function() {
if ( $(this).val() === '' )
flag=1;
});
如果您將使用jQuery,您可以檢查輸入字段是否為空並且還會捕獲空格/秒。 向所有輸入字段添加一個類,例如class =“required”,並為每個輸入字段添加具有相應值的屬性fieldname。
var requiredFields = "";
$("#myForm").find('.required').each(function () {
if ($(this).val().trim().length == 0) {
requiredFields += " - " + $(this).attr("fieldname") + "\n";
}
});
if (requiredFields != "") {
alert("Please enter the following required field(s): \n" + requiredFields);
} else {
//save here
}
您可以使用required
<input required type="text" name="email" id="log" />
或使用jQuery之類的
$("form").submit(function() {
var has_empty = false;
$(this).find('input').each(function() {
if(! $(this).val()) {
has_empty = true;
return false;
}
});
if(has_empty){return false;}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.