How to tell jQuery about appended form row
I've got a form that can have a row of items added via ajax. But when this row is added, the new inputs can't receive focus.
In trying to work this out, I discovered they do receive focus if an alert is triggered during the 开发者_开发问答bind function.
I have looked around for answers, but I just can't get it to work. I think "live" function might be related but I don't really get how to use it.
Here is my code.
$("#doogal").bind("click", function (event) {
$.ajax({data:$("#doogal").closest("form").serialize(), dataType:"html", success:function (data, textStatus) {$("#saleitems").append(data);}, type:"get", url:"\/saleitems\/add\/" + $rows});
$rows = $rows + 1;
// alert("uncomment this to enable focus");
$("#autoComplete_1").focus();
return false;
});
It sounds like a timing problem. $.ajax is an asynchronous call. When you have the alert commented out, the call to .focus() is happening before the ajax call is done and before the success function has been called and added the new input. When you add the alert, that delays the .focus() call long enough that the ajax call completes.
Put the .focus() (and probably the $row increment also) call in the success function so that it only runs after the ajax call is finished:
$("#doogal").bind("click", function (event) {
$.ajax({data:$("#doogal").closest("form").serialize(), dataType:"html", success:function (data, textStatus) {
$("#saleitems").append(data);
$rows = $rows + 1;
$("#autoComplete_1").focus();
}, type:"get", url:"\/saleitems\/add\/" + $rows});
return false;
});
Try giving the focus inside the callback function. Since you are using an AJAX which is asynchronous in nature, you will have to wait until the data gets loaded.
$("#doogal").bind("click", function (event) {
$.ajax({data:$("#doogal").closest("form").serialize(),
dataType:"html",
success:function (data, textStatus) {
$("#saleitems").append(data);
$rows = $rows + 1;
$("#autoComplete_1").focus();
},
type:"get",
url:"\/saleitems\/add\/" + $rows
});
return false;
});
精彩评论