54

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?

gdoron is supporting Monica
  • 136,782
  • 49
  • 273
  • 342
Richard Harris
  • 889
  • 3
  • 8
  • 14

7 Answers7

109
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

Community
  • 1
  • 1
gdoron is supporting Monica
  • 136,782
  • 49
  • 273
  • 342
  • 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. – Richard Harris May 18 '12 at 11:11
  • @RichardHarris. It should work fine in that case as well. there is something else in your code. see [this demo](http://jsfiddle.net/KGgaB/1/) – gdoron is supporting Monica May 18 '12 at 11:13
  • @RichardHarris. [Or this demo](http://jsfiddle.net/KGgaB/2/) used the css of codeparadox – gdoron is supporting Monica May 18 '12 at 11:17
  • Hmm. Trying to figure out why it doesn't work for me. Btw, your demo code is invalid because your div container closes immediately
    . Thanks for the help so far! Will update here when I can get it to work for me. Cheers!
    – Richard Harris May 18 '12 at 11:19
  • @RichardHarris. Did you find what was the problem yet? – gdoron is supporting Monica May 19 '12 at 21:49
  • 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. – Richard Harris May 20 '12 at 09:20
  • [value=""] does not work, but [value=] does. This answer is much better: http://stackoverflow.com/a/23321129 – personne3000 Sep 08 '16 at 08:58
  • @gdoron You might want to check it yourself before assuming you were right and disregarding others' comments... Here you go: https://jsfiddle.net/KGgaB/186/ – personne3000 Sep 08 '16 at 11:16
  • @personne3000, my bad. Sorry. Curious to know if it's documented somewhere... Anyway, you're right, I was wring. – gdoron is supporting Monica Sep 08 '16 at 16:38
  • 1
    @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. – gdoron is supporting Monica Sep 08 '16 at 19:44
  • @gdoron 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: https://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. – personne3000 Sep 09 '16 at 00:56
  • @personne3000 thanks for the follow-up. Please do edit and add your findings. – gdoron is supporting Monica Sep 09 '16 at 04:28
11
$('input:text[value=]','#sender_container').addClass('error');

DEMO

h0mayun
  • 3,259
  • 26
  • 39
3
$('#sender_container input.required[value=""]').addClass('error')
Parv Sharma
  • 11,976
  • 4
  • 43
  • 78
  • 1
    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... – gdoron is supporting Monica May 18 '12 at 11:42
  • 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? – Richard Harris Aug 12 '14 at 05:26
1
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.

gdoron is supporting Monica
  • 136,782
  • 49
  • 273
  • 342
thecodeparadox
  • 81,835
  • 21
  • 131
  • 160
  • either the inner or outer quotes need to be single, or escape the inner quotes. – Jamiec May 18 '12 at 10:59
  • @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 ;) – Felix Kling May 18 '12 at 11:01
  • @FelixKling Please check my demo – thecodeparadox May 18 '12 at 11:16
  • @FelixKling. That's weird, it looks like `:not[value...]` check the current state, $thecodeparadox, note that it's a bad selector to have. – gdoron is supporting Monica May 18 '12 at 11:20
  • I think he's saying it will assign class="error" to the value field, not the input element. – Richard Harris May 18 '12 at 11:21
  • @gdoron if it is a bad selector how it works? I show the proof – thecodeparadox May 18 '12 at 11:22
  • @thecodeparadox. It's slower by 50%. [jsperf proof](http://jsperf.com/attribute-not-vs-filter). 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! – gdoron is supporting Monica May 18 '12 at 11:25
  • 1
    @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. – Felix Kling May 18 '12 at 11:27
  • 1
    @gdoron yup, will never use it. should I remove this post or keep here to make another aware – thecodeparadox May 18 '12 at 11:29
  • 1
    @thecodeparadox Leave the code, it's a good learning tool, for future reference. – Richard Harris May 18 '12 at 11:32
0
$field = $("#sender_container input.required");
if( ! $field.val())
{
    $field.addClass("error");
}

this simple way may work.

Nils
  • 788
  • 1
  • 7
  • 24
  • 1
    $("#sender_container input.required").each(function( if( ! $(this).val()) { $(this).addClass("error"); })) try this. – Nils May 18 '12 at 11:30
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');
schmijos
  • 6,629
  • 3
  • 43
  • 50
0

to get all fields inspected this might help.

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

});
rmil
  • 56
  • 2