Charles Harmon
Charles Harmon

Reputation: 380

jQuery :empty not working with input

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/

Upvotes: 1

Views: 1645

Answers (3)

Rory McCrossan
Rory McCrossan

Reputation: 337743

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

Upvotes: 2

breq
breq

Reputation: 25526

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

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

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167250

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;

Upvotes: 0

Related Questions