Ragen Dazs
Ragen Dazs

Reputation: 2170

jQuery selector for empty value

How could I create a selector to use with .is() function in jQuery that represents the following expressions:

$('[name="Person[firstName]"]').val() === ''; // true
$('[name="Person[lastName]"]').val() === ''; // false

With this HTML context

<input name="Person[firstName]" value="" >
  <foo bar="true" />
</input>

<input name="Person[lastName]" value="ABCDEFGH" />

:empty Selector Select all elements that have no children (including text nodes).

 $('[name="Person[firstName]"]').is(':empty'); // false
 $('[name="Person[lastName]"]').is(':empty'); // true

Another try

$('[name="Person[firstName]"]').is('[value=""]'); // true
$('[name="Person[lastName]"]').is('[value=""]'); // true

Note: This is a question for knowledge purposes - and .is() must be used in this solution.

@edit http://jsfiddle.net/2CzWu/2/

It must return false on both expressions

Upvotes: 0

Views: 1071

Answers (1)

Ruan Mendes
Ruan Mendes

Reputation: 92274

The reason :empty doesn't work is because it's looking for nodes without child nodes, which is not what you are looking for.

$.is("[value='']") will only work with values that were set in the HTML initially, not as you update it whether through a script or by the UI. That is because the attribute selector looks at Node.getAttribute('value') === '' and the XML attribute is not updated when the DOM object is, but the DOM property HTMLInputElement.value does.

So what we really need is a custom pseudo selector that looks at the value DOM property and it's pretty simple to implement. It works with $.is and with :not()

$.expr[':'].emptyVal = function(obj){
   return obj.value === '';
};

var $firstName = $('[name="Person[firstName]"]');

$firstName.val('AAAA');

$('input:emptyVal').size(); // 2
$('input:not(emptyVal)').size(); // 0
$firstName.is('input:emptyVal'); // false
$firstName.is('input:not(:emptyVal)'); // true

Upvotes: 5

Related Questions