开发者

MVC partial View jQuery datepicker removing previous date pickers

I have a page where I am trying to add Children to a Parent object.

On the page, I have a link, "Add Child", that calls an ajax get, returning a partial view with textboxes for the Child. In the sucess, i am doing a function to add the results to the innerHTML of a div.

On the partial view, I have a textbox for the Birthdate, named "Birthdate{id}", where the {id} is a number based on how many have been added.

In the success method, I am then doing a

$("#BirthDate" + childAdded).datepicker();

This works great, for the latest Birthdate date picker. If I add 3 Children, the 3rd Child div's BirthDate will have a datepicker on load, but the 1st and 2n开发者_运维技巧d will lose the datepicker. Adding a 4th will then remove the datepicker from the 3rd.

Code:

function addChild() {
  $.ajax({
    type: "GET",
    url: "/Home/AddChild?childNumber=" + $("#CurrentNumberOfChildren").val(),
    data: "{}",
    contentType: "text/html",
    dataType: "html",
    success: function (results) {
      var div = document.getElementById('ChildDiv');
      div.innerHTML += results;
      $("#CurrentNumberOfChildren").val(parseInt($("#CurrentNumberOfChildren").val()) + 1);
      var numberOfChildren = $("#CurrentNumberOfChildren").val();
      $("#BirthDate" + numberOfChildren).datepicker();
    }
  });
}

Anyone ever run into this?


This line -- div.innerHTML += results; -- is rewriting the entire content of the div each time you add a new child section. This means that you're losing the event hooks etc on the elements that were previously in the div, even though the rewritten elements use the same ids etc. I suspect that this is what's breaking your datepickers.

To fix it you'll need to append the new content to what's already in the div, rather than rewriting the entire content every time. Try replacing these two lines:

var div = document.getElementById('ChildDiv');
div.innerHTML += results;

With this one:

$('#ChildDiv').append(results);


From what I can see you have probably got multiple elements sharing the same id. jQuery needs a valid dom to work correctly. You can validate your markup at w3c.

Can you add the response of the partial view to your question, also what version of jquery & ui?


I'm assuming that your partial view returns all of the textboxes, the previous ones plus the new ones since you are replacing the HTML of the div with the result. In that case, the previous elements (to which you added the datepickers) have been removed from the page. If that's the case then you'll need to re-add the datepickers to all of your BirthDate elements.


.live() – jQuery API

How about jQuey.live?

Though the change of selector is necessary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜