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

后端 未结 7 1486
遇见更好的自我
遇见更好的自我 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 01:16
    jQuery("#sender_container input.required").filter(function() {
        return !this.value;
    }).addClass("error");​
    

    Why you have to use filter and not [value=""] you can see in this DEMO

    The reason is: attribute selectors check the initial state of the element, not the current state. (note that you can change the "initial" state with the attr function, but it's bad practice, you should always use prop)

    So if you change the input value, the current value won't effect the attribute selector. not wise... :)

    Notes:

    • .val() returns the value of the form element, and breaks the jQuery chain, $('selector').val().addClass('foo') Error, the return value is a string\ number

    • .val(valueToSet) sets the value of the form element and doesn't break the jQuery chain.
      $('selector').val("some value").addClass('foo') - Valid, the returned value is a jQuery

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