Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

javascript - How to select empty inputs (value="") using jQuery

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:

jQuery("#sender_container input.required").val("").addClass("error");

But that seems to SET the value, rather than checking it. Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...