View Full Version : jQuery Odd behavior with jQuery Id Selector & If statement

09-04-2009, 09:30 PM
My jQuery if/else if statement is finding both conditions to be true - even if it is impossible for both to be true - and I can't figure out why.

I have a jQuery post that returns and inserts 1 of 2 forms into the page html. After inserting the form, a simple if/else if statement binds to the submit event a particular function based on which form is inserted. Below is the if/else if statement, anyone see what is wrong?

if ($("#nameSearch")) {
$("#showNames").click(function() { showChoices(sel); });
} else if ($("#addressSearch")) {
$("#showAddresses").click(function() { showChoices(sel); });

09-07-2009, 06:59 PM
Can you show us this in a working page? I'm not sure, but I think that the $() jquery selector might return something that equates as true even when the element ID you're looking for doesn't exist. Also, depending on where and how this code gets called, it might be run twice with different results. And if that does happen, nothing is removing the click handler from the buttons. It's difficult to say what's causing the behaviour without seeing the behaviour in action.

09-08-2009, 05:37 PM
Spudhead is correct-- a jQuery selector will always return an object (thus will always return true), even if the selector doesn't exist. Read this blog post for details how to test if a selector exists.


09-08-2009, 08:28 PM
this is a common misconception - perhaps rooted in that document.getElementById("blah") as per ecma specs needs to return object or false.

$("elementid") does same in mootools or prototype.

$("#elementid") looks the same in jquery but $ is the actual jquery object. if i remember correctly, change to if ($("#foo").length) instead, which would eval as 0/false if selector failed.

09-11-2009, 02:59 AM
Thanks all for the clarification; I was operating under the false impression that $("#element") returned either the object or false. Testing the length property resolved the issue.