Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If not disabled do this

Tags:

jquery

math

I am adding numbers entered into some inputs and getting a total. The totaling script works however now I want to not included the inputs to be counted if they are disabled. I am thinking I need to use :not(:disabled) but not sure how to put it into my script properly?

This is the script that counts:

$('.observationPositive').each(function(){
    countP++;
    sumP += Number($(this).val());
});

How do I say only count if not disabled? (wrongly coded example)

$('.observationPositive').each(function(){
    countP++;
    sumP += Number($(this:not(:disabled)).val());
});
like image 223
simple Avatar asked Jan 28 '13 18:01

simple


2 Answers

Only iterate over the ones that aren't disabled:

$('.observationPositive:not(:disabled)').each(function() {
   // increment count
});
like image 187
Jivings Avatar answered Oct 27 '22 13:10

Jivings


Your selector needs to be a string:

 $(this).is(":not(:disabled)");

This will return a boolean though. Calling val on a jQuery selector that matches no elements will return undefined and if you add undefined to a number you get NaN.

sumP += $(this).is(":disabled") ? 0 : Number($(this).val());    

In your particular case Jivings' answer is better.

like image 20
Matt Zeunert Avatar answered Oct 27 '22 12:10

Matt Zeunert