javascript - 检查并返回必填字段

标签 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!")
}

最佳答案

从头开始运行:

$(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
    }
  });
});

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

关于javascript - 检查并返回必填字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51298043/

相关文章:

sql - HTML5 Web SQL DB - 最大表大小?

javascript - 将数组上解析的字符串存储到另一个数组

javascript - 如何从字符串中 trim ()空格?

javascript - Angular Base64 图像在添加时未显示

javascript - 在 jQuery 中用户交互后逐个迭代 Python 提供的数组?

javascript - 如何使用 HTML/JS 实现 'human' 日期范围选择下拉列表? (今天、昨天、上周……)

javascript - 为什么我的 javascript 文件是唯一出现 404 错误的文件?

javascript - JQuery 滚动动画不粘在 DIV 内

具有所有嵌套元素的 Jquery Clone 对象

javascript - 我想为 appendChild() 设置动画,使其淡入