Reputation: 5163
I'm handling a checkbox.
if ($(this).hasClass("select")) { // To check class name
if ($(this).is(':checked')) { // to check whether it is checked
// some code
}
}
Now I have two if statements. How to merge them in a single condition?
I've tried:
1)
if ($(this).hasClass("select").is(':checked')) {
//statements
}
It gave me an error: .hasClass("...").is('...') is not a function
.
2)
if ($(this).hasClass("select") && $(this).is(':checked')) {
// some code
}
else if ($(this).hasClass("select") && $(this).not(':checked')) {
// some code
}
It's working.
How to merge these two in single statement in a simplified manner? Can we simplify the condition?
Upvotes: 0
Views: 685
Reputation: 67197
You can do it by,
var cond = $(this).is(".select:checked");
var val = parseInt($(this).parent().next().text());
sum += (cond ? val : -(val));
Upvotes: 1
Reputation: 92471
You can move the class checking into .is()
:
if ($(this).is(".select:checked"))
$(this).hasClass("select").is(':checked')
doesn't work because .hasClass()
returns boolean, not the $(this)
object, so you can't chain jQuery methods on it.
Upvotes: 0