Reputation: 63727
I am using the following jQuery code to count the number of text fields that have a value that is the same as its title attribute.
$(".textfield").val( $(".textfield").attr('title') ).size();
Problem: How do I count the number of text fields that do not have a value equal to its title attribute?
Upvotes: 1
Views: 355
Reputation: 150080
First of all, the code you post is not doing what you say it does. This:
$(".textfield").val( $(".textfield").attr('title') ).size();
Will set the value of all elements with class ".textfield" to the title of the first ".textfield" element's title attribute, and then return a count of all of them.
You need to compare the return of the .val()
method (with no parameter it returns the current value) with the return of the .attr('title')
method. You can do this with .filter()
and then check the .length
of the resulting jQuery object:
$('.textfield').filter(function() {
var $this = $(this);
return $this.val() == $this.attr('title');
}).length;
And then to get a count of those where the value is not equal just do the same thing except with !=
instead of ==
. So:
$('.textfield').filter(function() {
var $this = $(this);
return $this.val() != $this.attr('title');
}).length;
(Note that .length
will give you the same count as .size()
but without the overhead of a function call.)
Upvotes: 1
Reputation: 490657
I would use filter()
and then access the length
property of the returned set.
var count = $('.textfield').filter(function() {
return $(this).val() != $(this).attr('title');
}).length;
You could also probably get away with the body of filter()
as return this.value != this.title
.
Upvotes: 1
Reputation: 150313
filter
function.length
property of the selectorvar length = $('.textfield').filter(function() {
return this.value != this.title;
}).length;
Upvotes: 0