2

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"

1
  • You can use only css for this like describe in this answer. Commented May 30, 2018 at 8:55

3 Answers 3

1

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');
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I forgot to say that I have an input like this <div id="loginCard"><input type="text" /></div> I thought it worked anyway
0

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>

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.