检查并返回必填字段

时间:2018-07-12 05:40:37

标签: javascript jquery html

在将所有必填字段发送到数据库之前,我必须检查是否已填写所有必填字段。这是通过列IDKarakteristike完成的。如果该字段是必填字段,则此列的值为True,如果不是,则为False。 这是一个代码段:

https://jsfiddle.net/nzx3tdgp/

我需要以下代码的帮助。此代码需要更改,因此,如果所有必填字段均已填写,则返回true;否则,则返回false。 因为在此之后,我有一个ajax调用,如果返回true,则会将一些值发送到c#。

$(function () {
    $("#myButton").on("click", function () {
        // Loop all span elements with target class
        $(".IDKarakteristike").each(function (i, el) {
            // Skip spans which text is actually a number
            if (!isNaN($(el).text())) {
                return;
            }

            // Get the value
            var val = $(el).text().toUpperCase();
            var isRequired = (val === "TRUE") ? true :
                             (val === "FALSE") ? false : undefined;

            // Mark the textbox with required attribute
            if (isRequired) {
                // Find the form element
                var target = $(el).parents("tr").find("input,select");

                if (target.val()) {
                    return;
                }

                // Mark it with required attribute
                target.prop("required", true);

                // Just some styling
                target.css("border", "1px solid red");
            }
        });
    })
});

Ajax,它从某些字段和表中获取值并将其发送到c#。这应该在第一个函数返回true时触发(所有必填字段均已填写)

var ddl = $('#MainContent_ddlBusinessCenter').val()

var myCollection = [];

$('#MainContent_gvKarakteristike tbody').find('tr:gt(0)').each(function(i, e) {
  var row = $(e);
  myCollection.push({
    label: valuefromType(row.find(row.find('td:eq(1)').children())),
    opis: valuefromType(row.find(row.find('td:eq(3)').children()))
  });

});

console.log(myCollection);

function valuefromType(control) {
  var type = $(control).prop('nodeName').toLowerCase();


  switch (type) {
    case "input":
      return $(control).val();
    case "span":
      return $(control).text();
    case "select":
      ('Selected text:' + $('option:selected', control).text());
      return $('option:selected', control).text();
  }
}
var lvl = $('#MainContent_txtProductConstruction').val()
if (lvl.length > 0) {
  $.ajax({
    type: "POST",
    url: "NewProductConstruction.aspx/GetCollection",
    data: JSON.stringify({
      'omyCollection': myCollection,
      'lvl': lvl,
      'ddl': ddl
    }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",

    success: function(response) {
      if (parseInt(response.d) > 0)
        alert("Saved successfully.");
      else
        alert("This object already exists in the database!");
      console.log(response);
      location.reload(true);
    },
    error: function(response) {
      alert("Not Saved!");
      console.log(response);
      location.reload(true);
    }
  });
} else {
  alert("Please fill in the Product Construction field!")
}

2 个答案:

答案 0 :(得分:2)

仅将click函数之外的全局变量用作变量吗?

//make a variable
var ajaxCheck;

$(function () {
    $("#myButton").on("click", function () {
        //put your condition here, this can be inside a loop:
        if (hasValue) {
            ajaxCheck = true;
            //either use your ajax check in your ajax call or put ajax code here
        } else {
            ajaxCheck = false;
        }
    });
});

答案 1 :(得分:2)

只需从头开始运行即可:

$(function() {
  $(".IDKarakteristike").each(function(i, el) {
    if ($(el).text().toUpperCase() === "TRUE") {
      $(el).closest("tr").find("input,select").prop("required", true);
    }
  });

  $("#myButton").on("click", function() {
    var ok = true;
    $("[required]").each(function() {
      $(this).css("border", "1px solid black"); // reset

      if (!$(this).val()) {
        ok = false;
        $(this).css("border", "1px solid red");
      }
    });
    if (ok) {
      // do what you need here
    }
  });
});

您还可以将按钮设置为“提交”按钮,并在提交时阻止“ DefaultDefault”-然后可以将所有必填字段设为“必填”,浏览器将停止提交并为您显示错误消息

相关问题