2

Possible Duplicate:
Why does jQuery or a DOM method such as `getElementByID` not find the element?

I load the file using jquery.load(). In my load_to.html I am targeting the element with id as

$('#users').change(function() {
  alert('hello');
});

this element is present in load_from.html. I couldn't able to target this. But when I inspect the page I can able to see this element.

I loaded the page like this

$('#mydiv').load('/user/1/edit form');

How to target the element?

Community
  • 1
  • 1
Achaius
  • 5,326
  • 16
  • 59
  • 107

2 Answers2

6

Use on in it's delegate signature:

$('#mydiv').on('change', '#users', function() {
  alert('hello');
});

Read the docs

gdoron is supporting Monica
  • 136,782
  • 49
  • 273
  • 342
  • interesting how no-one is upvoting Questioners. People who really need votes. :) Happy New Year bro! +1 – Roko C. Buljan Jan 02 '13 at 16:27
  • @roXon, it could be a good question if it wasn't so commonly asked, it's even in [jQuery FAQ](http://docs.jquery.com/Frequently_Asked_Questions#Why_do_my_events_stop_working_after_an_AJAX_request.3F) btw, they show the way with the binding in the load function(mcpDESIGNS) AND my way... – gdoron is supporting Monica Jan 02 '13 at 16:49
1

Try to set up your events in the callback from .load to make sure they are created once the elements enter the DOM.

$('#mydiv').load('/user/1/edit form', function () {

    //Callback
    //set up events here (once it is finished loading)

    $('#users').change(function() {
        alert('hello');
    });
});
Mark Pieszak - Trilon.io
  • 44,537
  • 13
  • 74
  • 89
  • again no no and no, it's not wrong but it's not the way somsone should write jQ. that's why we have the (ex .live() ) `.on()` method. A load callback should not carry future events, at least not for a legible code. inside a load c.b. you expect to see some features that will happen after a success response, not to see events delegation. – Roko C. Buljan Jan 02 '13 at 15:59
  • @roXon, Actually I see nothing wrong with this approach, I'm upvoting this as it's perfectly valid! +1 – gdoron is supporting Monica Jan 02 '13 at 16:07
  • @gdoron don't push me to upvote this answer, cause **yes**, it's perfectly correct, just trying to share my thoughts and a way to write logic code. – Roko C. Buljan Jan 02 '13 at 16:25
  • @roXon Well at the same time using delegated stuff works great, I like how wrapped together this is. Obviously the page being loaded should have it's own events / JS set up. I just personally think it can be confusing to have delegated events only to do with a `load`'d page within the parent. – Mark Pieszak - Trilon.io Jan 02 '13 at 16:39