views:

369

answers:

3

I am new to jQuery and cannot get a selector to work using the id of the element. The code below works:

$(function() {  
  /* $("#ShowBox").onclick = ShowAccessible;  */  
  document.getElementById("ShowBox").onclick = ShowAccessible;  
  /* $(".searchcheck").click = ShowAccessible; */  
});

function ShowAccessible() {  
  $("tr.hide").fadeOut();  
}

However, neither of the two commented out lines work i.e. they do not apply the click event to a checkbox named "ShowBox" with a class of "searchcheck". Why is this?

+8  A: 

there is no onclick property for a jQuery object; when you use $([selector]), a jQuery object is returned, not an element.

Use either

.click(function () { ...}); // can be an anonymous function or named function

or

.bind('click', function() { ... }); // can be an anonymous function or named function

like so

$("#ShowBox").click(ShowAccessible);
$("#ShowBox").bind('click', ShowAccessible);
Russ Cam
Oops, typo - this does not work either <pre>$("#ShowAccessible").click = ShowAccessible;</pre>
yuben
I've updated with an example
Russ Cam
+6  A: 

JQuery uses functions rather than properties to set the handlers.

$("#ShowBox").click(ShowAccessible); 
Tom Hubbard
Thanks Tom. I misread the tutorial which has an example of this.
yuben
A: 

if you really had to do it with an assignment , i think

$("#ShowBox")[0].onclick = ShowAccessible;

would work.

gene tsai