Reputation: 717
Until jQuery 1.8.3 I could get empty input using this code
$('#loginCard input[value=]').addClass('error');
After jQuery 1.8.3 this syntax does not work. What has changed?
I'd like to do the same thing with jQuery 3.2.1 without using functions or each like here:
$('#loginCard input').each(function (){
if($(this).val()==""){
$(this).addClass("error");
}
});
following the concept "write less, do more"
Upvotes: 2
Views: 109
Reputation: 5013
Even though using quotes works, using $item.val()
and using a CSS-Selector is not the same, as the latter doesnt' respect user input. Therefore the CSS-Selector-Solution will always display an error, even though the input is no longer empty:
https://codepen.io/MattDiMu/pen/aKzbgw
Upvotes: 0
Reputation: 2486
Your Code Work in Steel This version, I hope your another problem affected this section. You Can Also Try This Code Here https://jsfiddle.net/tzk4a593/ Or Follow this code
jQuery("#loginCard").find('input').each(function (){
if($(this).val()==""){
$(this).addClass("error");
}
});
input.error { border: 1px solid red; }
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<form id="loginCard" action="#">
<input type="text" value="" name="one" />
<input type="text" value="xxxxxx" name="some" />
<input type="text" value="" name="two" />
<input type="text" value="myVal" name="three" />
</form>
Upvotes: 0
Reputation: 337560
The fact it worked without the quotes is a bug/feature which shouldn't have even been allowed in 1.8.3.
Add quotes, eg. [value=""]
, and it works fine in any version of jQuery, past or present:
$('#loginCard input[value=""]').addClass('error');
.error { border: 1px solid #C00; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="loginCard">
<input type="text" value="" />
</div>
If you need an alternative method to the attribute selector, you can use filter()
like this:
$('#loginCard input').filter(function() {
return $(this).val().trim() == '';
}).addClass('error');
Upvotes: 1