maniak
maniak

Reputation: 462

JQuery Ajax not updating DOM (I think)

I have a problem, in my page, I have a div that contains lets say two hidden fields with the value 0 and 2. I have a button that trigger an ajax query and change the div contents with the same hidden fields but with the value 1 and 2 respectively. The problem is that it seems like my javascript (using JQuery) is not aware of theses changes. When I inspect my page to see the html source code I see the values have changed but in the script when I'm doing:

$("#btn").click(function() {
    alert($("#hidden1").val());
    alert($("#hidden2").val());
});

It still show me the old value (0 and 2) like if the DOM hasn't been updated. Can someone help me please or tell me if it is normal and how to fix it.

Thanks for your time Me!

Upvotes: 0

Views: 2316

Answers (2)

Nick Beranek
Nick Beranek

Reputation: 2761

Try this:

$("#btn").on('click', function() {
  alert($("#hidden1").val());
  alert($("#hidden2").val());
});

Upvotes: 1

Kekoa
Kekoa

Reputation: 28250

It's not that the DOM is not being updated, it's probably because your jQuery event is bound to the particular element at the time .click() is called. Since the DOM changed(you likely removed and added a new element of the same id), the function returns the values of the elements you discarded(because it remains bound to it even if removed from DOM).

Use the live() method or on() as a replacement for your click() handler. This method provided by jQuery will not bind to a particular DOM element at the time it is called, but does a dynamic lookup every time a click is detected.

Upvotes: 0

Related Questions