2

hi i have table on the form. when page load is fired i set focus to the first input[type='text']. and i post the form with ajax and if all goes right i add new row to the top of the table. and now i cant set focus to new inserted row.here is my javascript code:

  $(document).keypress(function (e) {
            var key_code = e.which;
            if (key_code == 13) {
                $.ajax({
                    type: "POST",
                    url: "AddNewPayPackage",
                    data: $("#AddPackPayment").serialize(),
                    dataType: "text/plain",
                    success: function (response) {
                        if (response == "Saved") {
                            $('#myTable tbody tr:first input:text').removeAttr("tabindex");

                            $.get('AddNewPayPackage', function (data) {
                                $('#myTable tbody tr:first').before("<tr>" + data + "</tr>");
                            });

                            $('.input-validation-error').removeClass('input-validation-error');
                            $("form :input[type='text']:first").focus();
                        }
                        else {
                            $("#myTable tbody tr:first").html(response);
                        }
                    }
                });
            }
        });    
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
AEMLoviji
  • 3,217
  • 9
  • 37
  • 61

2 Answers2

6

The problem is that your element added in the $.get() callback is added later, when the server response comes back with the content...so you need to focus after that happens...in the callback, like this:

$.get('AddNewPayPackage', function (data) {
    $('#myTable tbody tr:first').before("<tr>" + data + "</tr>");
    $("form :input[type='text']:first").focus(); //needs to run here
});
$('.input-validation-error').removeClass('input-validation-error');
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • you are great. i did not know it. yes $.get() callback is added later when the server response comes back. but i set the focus after this callback block. why it work so? – AEMLoviji Dec 18 '10 at 13:04
  • @AEMLoviji - not sure how to explain it better than...that's how all asynchronous operations work, use the callback to do work that needs to be done after they're complete, the same goes with the `success` or `complete` functions in the full `$.ajax()` version. – Nick Craver Dec 18 '10 at 13:05
1

Looks like a typo:

$("form :input[type='text']:first").focus();

should be

$("form input[type='text']:first").focus();
Stuart Burrows
  • 10,824
  • 2
  • 34
  • 33
  • Either of these will work...though since we're dealing with an `` the second *is* more efficient, and what I'd go with. – Nick Craver Dec 18 '10 at 12:58