1

I am having a problem in using jQuery's :empty pseudo selector. Basically, it isn't working on inputs the way I think it should. Given this html, I'm trying to get a count of all the inputs which don't have values without a loop.

<div id="sampleDiv">
<label>My first Input:</label>
<input name="test" id="firstInput" type="text" value="default text" /><br/><br/>
<label>My second Input:</label>
<input name="test" id="secondInput" type="text" value="" /><br/><br/>
<label>My third Input:</label>
<input name="test" id="thirdInput" type="text" value="" />

I'm using a selector like this

$('#sampleDiv input:empty').length

but it's returning 3, including the one with the value. Here is the fiddle and thanks for any help here!: https://jsfiddle.net/chas688/b5fad3Lu/

3 Answers 3

2

The :empty selector is designed to look through the children of an element. This is why it doesn't necessarily work for you in this instance. Instead, you can select by the value attribute:

$('#sampleDiv input[value=""]').length;

Example

Or by filter():

$('#sampleDiv input').filter(function() {
    return this.value == '';
}).length;

Example

Sign up to request clarification or add additional context in comments.

8 Comments

@PraveenKumar thanks - I even copied and pasted that. Not sure how I messed it up, lol.
Thanks, that makes a lot of sense now, it was a bit misleading on the W3c selectors reference: w3schools.com/jquery/jquery_ref_selectors.asp
Note that W3Schools has nothing to do with the W3C and are a bunch of..... See w3fools.com for more info. I'd suggest never using their site.
Also, glad to help :)
W3Schools even uses $("input:not(:empty)") in their example on how to use :not. I guess they missed a not somewhere in there.
|
0

The :empty stands for empty HTML and not empty values! You have to use this way:

count = 0;
$('#sampleDiv input').each(function () {
  if ($(this).val().length == 0)
    count++;
});

Or use .filter():

$('#sampleDiv input').filter(function() {
    return ($(this).val().trim().length == 0);
}).length;

Comments

0

This one works for all input text. https://jsfiddle.net/b5fad3Lu/2/

var pl = $('input:text[value=""]').length;
$('#numberofEmpty').text( pl );

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.