0

I'm having a bit of a jQuery problem. Basically I have some functions that I need to place inside the ready function so that they have scope access to some of the objects initialized on document ready. However, for whatever reason, no methods created seem to respond to any of the DOM objects' onClick. I am forced to pull them outside the $(). I'm sure there is some elementary point I'm missing here, but I can't seem to see it. Any ideas?

FYI (to anyone interested) for this particular problem, I am working with datatables (http://www.datatables.net/) and need to provide a few functions access to the initialized table(s).

Best.

Greg Pettit
  • 10,749
  • 5
  • 53
  • 72
humble_coder
  • 2,777
  • 7
  • 34
  • 46
  • Yes, what you say doesn't make sense. See simple example - http://jsfiddle.net/P4FVn/ If you can edit this to show your problem it would be awesome. – mrtsherman Nov 15 '11 at 21:42

1 Answers1

1

Rather than using inline onclick handlers, add your event handlers within the $():

$(function () {
    //...functions here
    $('a.click-me').on('click', function () {
        //call function here for clicking on the link with the `click-me` class
    });
});

That way the click handlers have access to the variables inside the anonymous function that runs when document.ready fires.

Jasper
  • 75,717
  • 14
  • 151
  • 146
  • I agree in principle. In specifics, if his implementation of DataTables does any DOM node destruction, he'll need to use `.on()` to delegate an ancestor listener instead of listening to self. – Greg Pettit Nov 15 '11 at 21:46
  • Well, I'm using a form and attempting to "short-circuit" the SUBMIT if JS is available. So I basically do a "form.serialize" and submit the data then use a "successful" ajax return to then manipulate the table on the page. The problem is that the button 'onClick="delete_item()"' method won't run unless I pull it outside. Perhaps I should use a non-descript button instead of an official "submit"? – humble_coder Nov 15 '11 at 21:49
  • @GregPettit: Yes, I need to actually remove nodes after successful backend deletion. – humble_coder Nov 15 '11 at 21:51
  • Jasper still has it right. You can bind to a "submit" button just fine; all you have to do is preventDefault() on the event. – Greg Pettit Nov 15 '11 at 22:05
  • Wow, it helps if your "preventDefault" ends in "()" ... *facepalm* ... Thanks. – humble_coder Jun 01 '12 at 21:11