I have two forms, form 1 and form 2; both forms are located in same document or page. These forms are differentiated by a checkbox; form 1 has a checkbox input element, and form 2 has not checkbox element within.
Currently, i am trying to test for the existence of the checkbox input element with the following code:
if(jQuery(this).closest("form").find(':checkbox')){...}
when I click form 2 submit, checkbox is found.
As of now, I understand that .closest will set the context to the closest form element found. And If am triggering form 2, which has no checkbox, why is it finding the checkbox of form 1?
Obviously I have misunderstood how this works. Could somebody explain?
I think the reason for your problem is that all jQuery selections are truthy. Even an empty jQuery selection will pass an
ifcondition:You have to check the
lengthproperty to see if any elements are found:If there are no elements found, the
lengthwill be0, which is a false-y value, so the conditional will fail. If any elements are found, thelengthwill be greater than0, so the conditional will pass.