簡體   English   中英

檢查必填字段是否為空

[英]Check whether the required field is not empty

我想檢查必填字段是否為空。 我用下面的代碼。

$(":input").each(function() {
    if($(this).data('label')=='required')
     {
        if($(this).val() === "")
        alert("Empty Fields!!");
     }
});

但這是不只一次的警覺。 JSFiddle: http : //jsfiddle.net/hbk2a5qo/3/

為什么不直接在HTML中使用required屬性:

<input id="name"type="text" data-label="required" required/>

您需要使用一個標志

$(document).ready(function () {

    $("#submit").click(function (e) {
        e.preventDefault()
        AlertSave();
    });
});

function AlertSave() {
    //use the flag to set the valid status in the loop
    var valid = true;
    //iterate over only the required elements
    $(':input[data-label="required"]').each(function () {
        if ($(this).val() === "") {
            valid = false;
            return false;
        }
    });

    if (valid) {
        //do your save
    } else {
        alert("Empty Fields!!");
    }
}

演示: 小提琴

由於使用了$(":input").each()因此它將遍歷所有字段。 但是您可以使用標志僅顯示一次警報。

function AlertSave() {
var alertShown=false;   
    $(":input").each(function() {
        if($(this).data('label')=='required')
                        {
   if($(this).val() === "" && !alertShown)
   {
       alertShown=true;
        alert("Empty Fields!!");
   }
  }
});
    }

您更新了小提琴

通過使用required屬性(推薦),這將返回所有沒有value的必需輸入字段:

var inputsWithMissingValues = $('input[required]').filter(function(i, input) {
  return !input.value.length;
});

因此,如果長度大於零,則您必須填寫缺少值的字段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM