Check if inputs are empty using jQuery

前端 未结 18 850
灰色年华
灰色年华 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: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!');
      }
    });
    
    
    

    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.

提交回复
热议问题