How to select empty inputs (value=“”) using jQuery

后端 未结 7 1485
遇见更好的自我
遇见更好的自我 2020-12-03 00:31

How can I check for empty values of (required) input fields within a section, and then add a class to them on an event, using jQuery? So far, I have tried:

相关标签:
7条回答
  • 2020-12-03 00:55
    jQuery('#sender_container input.required[value=""]').addClass("error");
    

    You can try this:

    $('input:not([value!=""])').addClass('error');
    

    DEMO

    Note: This answer should not be used, and the only reason it wasn't deleted is so it can be learned from.

    0 讨论(0)
  • 2020-12-03 00:58

    to get all fields inspected this might help.

    $('#sender_container [required]').each(function(index)
    {
           if (!($(this).val())) $(this).addClass('error');
    }
    
    });
    
    0 讨论(0)
  • 2020-12-03 01:01

    If you only need to select based on the initial attribute value of the input then the following will do:

    var elements = $('#sender_container input.required[value=""]')
    

    But be aware that this won't work if the value attribute isn't present. It also won't work for the current input value if it has been changed by user or script.

    If you'd like to get the current input value you can use jquery's filter function:

    var elements = $('#sender_container input.required').filter(function() {
      return this.value === '';
    
      // alternatively for "no value":
      // return !this.value;
    })
    

    After you've selected the jquery elements you can add your class:

    elements.addClass('error');
    
    0 讨论(0)
  • 2020-12-03 01:05
    $field = $("#sender_container input.required");
    if( ! $field.val())
    {
        $field.addClass("error");
    }
    

    this simple way may work.

    0 讨论(0)
  • 2020-12-03 01:07
    $('#sender_container input.required[value=""]').addClass('error')
    
    0 讨论(0)
  • 2020-12-03 01:09
    $('input:text[value=]','#sender_container').addClass('error');
    

    DEMO

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