jQuery check if <input> exists and has a value

后端 未结 7 890
情歌与酒
情歌与酒 2021-02-01 00:07

I have the following example:


Is there a way to check if this element exists and ha

7条回答
  •  灰色年华
    2021-02-01 00:54

    You can create your own custom selector :hasValue and then use that to find, filter, or test any other jQuery elements.

    jQuery.expr[':'].hasValue = function(el,index,match) {
      return el.value != "";
    };
    

    Then you can find elements like this:

    var data = $("form input:hasValue").serialize();
    

    Or test the current element with .is()

    var elHasValue = $("#name").is(":hasValue");
    

    jQuery.expr[':'].hasValue = function(el) {
      return el.value != "";
    };
    
    
    var data = $("form input:hasValue").serialize();
    console.log(data)
    
    
    var elHasValue = $("[name='LastName']").is(":hasValue");
    console.log(elHasValue)
    label { display: block; margin-top:10px; }
    
    
    

    Further Reading:

    • Make jQuery :contains Case-Insensitive
    • Make Your Own Custom jQuery Selector
    • Exploring jQuery Selectors, Part 3

提交回复
热议问题