Reputation: 35
I know that in php that ||
is an 'or' operator but how can I use it in jQquery?
if ($("#shift1" || "#shift2" || "#shift3").is(":checked")){
$('#mon').css({
'background-color': '#88CC44',
'color':'white'
});
} else {
$('#mon').css({
'background-color': 'grey',
'color':'white'
});
}
I want this to work if any of #shift1
or #shift2
or #shift3
is checked but so far it only works for the id selected first on the list. How is this done in jQuery, and also what about an 'and' instead of an 'or' is it &&
?
Upvotes: 2
Views: 1632
Reputation: 613
Can also make something like this, which allow you to add other checkbox without changing your javascript.
$('#mon').css({
'background-color': $('[id^="shift"]:checked').length > 0 ? '#88CC44' : 'grey',
'color':'white'
});
$('[id^="shift"]:checked')
looks for checked element width an id that begins with the string shift
Upvotes: 1
Reputation: 337560
The ||
is the 'or' operator in JavaScript too - however in a selector it doesn't work with that syntax. jQuery selectors use CSS syntax, so to select multiple elements (aka an 'or' operation) you separate them by comma:
$("#shift1, #shift2, #shift3")
Also note that you can simplify and DRY your code with the use of a ternary:
$('#mon').css({
'background-color': $("#shift1, #shift2, #shift3").is(":checked") ? '#88CC44' : 'grey',
'color':'white'
});
Upvotes: 3