Michael BW
Michael BW

Reputation: 1070

jquery function works with live, not with on

trying to use the preferred on method call but the code is not working with on but does work with the live method.

Okay, I have a simple button element.

<button id="EditVal" name="EditVal" style="btn" value="Edit Debt">Edit Debt </button>

If I use the live method this code works:

$("#EditVal").live("click", function(e){
    alert('Edit this Val');
})

But this doesn't

$("#EditVal").on("click", function(e){
    alert('Edit this Val');
})

What am I doing wrong?

Upvotes: 3

Views: 219

Answers (4)

Marcus
Marcus

Reputation: 5153

The logic is that .on() binds the event to an object that is in the DOM. Then you give, as a parameter, the selector to find the child-element you want the trigger the event.

$("#parent_has_to_be_in_dom").on("click", "#myButton", function(event) {
    // should work like live
    alert("well hello");
});

Upvotes: 2

Al Katawazi
Al Katawazi

Reputation: 7240

If your dynamically dropping a html element on the page then you need live. Here is why, on is set to work on EditVal if EditVal exsists on pageload. Since it does not I am assuming, the live function is needed as that can be bounded late after the initial page load. I think that was the original thought behind live in the first place. Any particular reason why you are using on instead of live?

Upvotes: 3

Rory McCrossan
Rory McCrossan

Reputation: 337733

Using on as you are attaches the event on page load. As you are dynamically loading the content, you need to use on as you would delegate by placing the handler on a parent element, and passing a filtering selector.

Try this:

$("#ParentOfEditVal").on("click", "#EditVal", function(e){
    alert('Edit this Val');
})

Upvotes: 4

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 263167

You're using on() like bind(), not like live(). To use it like live(), you should write:

$(document).on("click", "#EditVal", function(e) {
    alert('Edit this Val');
});

Note that, for performance reasons, it's preferred to call on() on a non-dynamic ancestor element instead of document, i.e. to use it like delegate() instead of live().

Upvotes: 9

Related Questions