user3861559 user3861559 - 2 months ago 7
Javascript Question

More than one selector in Jquery if statement

I have 2 statements like this:

if ($('#lcheckbox').prop('checked')) {
ajaxData.mktgoptin=$form.find("[name='optin']").val();
}


and

if($("input[type='hidden'][name='optin']").length) {
ajaxData.mktgoptin=$form.find("[name='optin']").val();
}


Since what happens in the if condition is the same, I am wondering it there is way combine them into one. I tried Or operator, multiple selector trick but no avail. Any tips?

Answer

You can use the Or operator "||" to combine the two conditions :

if ( $('#lcheckbox').prop('checked') || $("input[type='hidden'][name='optin']").length) {
// your code
}

That's work on the exemple https://jsfiddle.net/jg92g5oe/