检查所有表单输入是否都填充了Jquery并执行某些操作

时间:2014-07-08 18:30:22

标签: jquery

我想隐藏提交按钮并仅在我的表单的所有输入都填入值时显示。

我试试这个,但它不起作用。

<script type="text/javascript">
$(document).ready(function() {

    var $fields = $("#new_account_form :text, :file, :checkbox, select, textarea");
    $fields.keyup(function() {
        var $emptyFields = $fields.filter(function() {

            // remove the $.trim if whitespace is counted as filled
            return $.trim(this.value) === "";
        });

        if (!$emptyFields.length) {
           $('#submitAccount').show();
        } else {
            $('#submitAccount').hide();
        }
    });
});?
</script>

1 个答案:

答案 0 :(得分:0)

我认为你正在寻找这样的东西。下面显示的是用于验证表单中的所有下拉列表和文本控件。同样,您需要迭代所有checkboxes和其他控件,并相应地设置count值。

function validateInputs() {
  var count = 0;

   // for all dropdowns with class as .dropdown
   $('.dropDown').each(function (index, item) {
      var selectedValue = $("option:selected", $(this)).val();
      if (selectedValue == "0" || $(this).find('option').length <= 1) {
         count = 1;
         $(this).css('border-color', '#ff0000'); // optional if you want to change the border color to indicate a required field
     }
   }, 0);

    // for all textbox in the page
    $('form input[type="text"]').each(function (index, item) {
      if ($.trim($(this).val()) == "") {
        count = 1;
        $(this).css('border-color', '#ff0000'); // optional if you want to change the border color to indicate a required field
      }
     }, 0);

  if (count == 1) {
      $('#submitAccount').hide();
  }
  else {
      $('#submitAccount').show();
  }
}

您可以调用该函数来验证来自$(document).ready

的所有表单输入
$(function () {
   validateInputs ();
});