How to select empty inputs (value="") using jQuery
Asked Answered
M

7

58

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?

Mathes answered 18/5, 2012 at 10:57 Comment(0)
O
117
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

Ourself answered 18/5, 2012 at 10:58 Comment(12)
Thanks but this only works if ALL the inputs are empty. But if I have 2 required fields, and one has a value and the other is empty, nothing happens.Mathes
@RichardHarris. It should work fine in that case as well. there is something else in your code. see this demoOurself
@RichardHarris. Or this demo used the css of codeparadoxOurself
Hmm. Trying to figure out why it doesn't work for me. Btw, your demo code is invalid because your div container closes immediately <div id="foo" />. Thanks for the help so far! Will update here when I can get it to work for me. Cheers!Mathes
@RichardHarris. Did you find what was the problem yet?Ourself
No, but after making some changes to other code in my scripts it worked. So it was something else, and not your code, that was the problem. Wish I knew exactly what it was.Mathes
[value=""] does not work, but [value=] does. This answer is much better: stackoverflow.com/a/23321129Algonquian
@Ourself You might want to check it yourself before assuming you were right and disregarding others' comments... Here you go: jsfiddle.net/KGgaB/186Algonquian
@personne3000, my bad. Sorry. Curious to know if it's documented somewhere... Anyway, you're right, I was wring.Ourself
@personne3000, if it's not documented as officially supported, I would never use it as it looks a bit hacky. But if it does, that's a great way! Thank you for proving me wrong sir.Ourself
@Ourself Agreed about the documentation point; so I did some research to clear this up, and it turns out you are not actually wrong. jQuery < 1.9 (jsfiddle uses 1.7.2 for some reason) have inconsistent behavior with attribute selectors, which makes this hack work. jQuery 1.9+ works as you described; see the release notes for details on the change: jquery.com/upgrade-guide/1.9/#attr-versus-prop- ; jQuery 1.11+, 2.x and 3.x even throws a Syntax error, so the method I recommended previously is actually very wrong. I might edit your post to add this info.Algonquian
@Algonquian thanks for the follow-up. Please do edit and add your findings.Ourself
C
11
$('input:text[value=]','#sender_container').addClass('error');

DEMO

Cyst answered 27/4, 2014 at 8:29 Comment(1)
This will not work in jQuery 1.9+, see jquery.com/upgrade-guide/1.9/#attr-versus-prop-Algonquian
P
3
$('#sender_container input.required[value=""]').addClass('error')
Plasmolysis answered 18/5, 2012 at 10:58 Comment(2)
Actually it will not work at all, there is a wrong space between the input and the attribute selector... :) it will search for children of input with an empty value attribute, input can't have children...Ourself
Thanks, Parv. Your code should now work for any children of a containing element with id sender_container that is an input field using class required and whose value is empty, correct?Mathes
M
2
jQuery('#sender_container input.required[value=""]').addClass("error");

You can try this:

$('input:not([value!=""])').addClass('error');

DEMO

Note: This answer should not be used, and the only reason it wasn't deleted is so it can be learned from.

Moradabad answered 18/5, 2012 at 10:58 Comment(10)
either the inner or outer quotes need to be single, or escape the inner quotes.Waugh
@gdoron: Never mind, I tried it, it didn't work... strange, must have been something else then. But it definitely was related to the selectors and input field values ;)Langtry
@FelixKling Please check my demoMoradabad
@FelixKling. That's weird, it looks like :not[value...] check the current state, $thecodeparadox, note that it's a bad selector to have.Ourself
I think he's saying it will assign class="error" to the value field, not the input element.Mathes
@Ourself if it is a bad selector how it works? I show the proofMoradabad
@thecodeparadox. It's slower by 50%. jsperf proof. And the fact that it's weird it even works, is a huge drawback. I wouldn't use it, I hope neither do you. Good luck mate!Ourself
@gdoron: I think it's the != and that's probably what I was referring to earlier, but could not properly remember. I assume, since [attr!=value] is not a CSS3 selector (afaik), it's evaluated by Sizzle and it seems to take the actual value. @thecodeparadox: Only because it works, does not mean it should be used. Double negations are difficult to understand as well.Langtry
@Ourself yup, will never use it. should I remove this post or keep here to make another awareMoradabad
@Moradabad Leave the code, it's a good learning tool, for future reference.Mathes
C
0
$field = $("#sender_container input.required");
if( ! $field.val())
{
    $field.addClass("error");
}

this simple way may work.

Clostridium answered 18/5, 2012 at 11:16 Comment(1)
$("#sender_container input.required").each(function( if( ! $(this).val()) { $(this).addClass("error"); })) try this.Clostridium
P
0

If you only need to select based on the initial attribute value of the input then the following will do:

var elements = $('#sender_container input.required[value=""]')

But be aware that this won't work if the value attribute isn't present. It also won't work for the current input value if it has been changed by user or script.

If you'd like to get the current input value you can use jquery's filter function:

var elements = $('#sender_container input.required').filter(function() {
  return this.value === '';

  // alternatively for "no value":
  // return !this.value;
})

After you've selected the jquery elements you can add your class:

elements.addClass('error');
Please answered 10/2, 2016 at 10:13 Comment(0)
B
0

to get all fields inspected this might help.

$('#sender_container [required]').each(function(index)
{
       if (!($(this).val())) $(this).addClass('error');
}

});
Bailes answered 19/6, 2017 at 12:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.