Check if inputs are empty using jQuery

前端 未结 18 840
灰色年华
灰色年华 2020-11-22 09:14

I have a form that I would like all fields to be filled in. If a field is clicked into and then not filled out, I would like to display a red background.

Here is my

相关标签:
18条回答
  • 2020-11-22 09:25
    $(function() {
      var fields = $('#search_form').serializeArray();
      is_blank = true;
      for (var i = 0; i < fields.length; i++) {
        // excluded fields
        if ((fields[i].name != "locale") && (fields[i].name != "utf8")) {
          if (fields[i].value) {
            is_blank = false;
          }
        }
      }
      if (is_blank) {
        $('#filters-button').append(': OFF');
      }
      else {
        $('#filters-button').append(': ON');
      }
    });
    

    Check if all fields are empty and append ON or OFF on Filter_button

    0 讨论(0)
  • 2020-11-22 09:26

    how come nobody mentioned

    $(this).filter('[value=]').addClass('warning');
    

    seems more jquery-like to me

    0 讨论(0)
  • 2020-11-22 09:27

    function checkForm() {
      return $('input[type=text]').filter(function () {
        return $(this).val().length === 0;
      }).length;
    }

    0 讨论(0)
  • 2020-11-22 09:28
    <script type="text/javascript">
    $('input:text, input:password, textarea').blur(function()
        {
              var check = $(this).val();
              if(check == '')
              {
                    $(this).parent().addClass('ym-error');
              }
              else
              {
                    $(this).parent().removeClass('ym-error');  
              }
        });
     </script>// :)
    
    0 讨论(0)
  • 2020-11-22 09:30

    The :empty pseudo-selector is used to see if an element contains no childs, you should check the value :

    $('#apply-form input').blur(function() {
         if(!this.value) { // zero-length string
                $(this).parents('p').addClass('warning');
         }
    });
    
    0 讨论(0)
  • 2020-11-22 09:33

    Great collection of answers, would like to add that you can also do this using the :placeholder-shown CSS selector. A little cleaner to use IMO, especially if you're already using jQ and have placeholders on your inputs.

    if ($('input#cust-descrip').is(':placeholder-shown')) {
      console.log('Empty');
    }
    
    $('input#cust-descrip').on('blur', '', function(ev) {
      if (!$('input#cust-descrip').is(':placeholder-shown')) {
        console.log('Has Text!');
      }
      else {
        console.log('Empty!');
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <input type="text" class="form-control" id="cust-descrip" autocomplete="off" placeholder="Description">

    You can also make use of the :valid and :invalid selectors if you have inputs that are required. You can use these selectors if you are using the required attribute on an input.

    0 讨论(0)
提交回复
热议问题