简体   繁体   中英

.focus() doesn't work on element created by jQuery dynamically

Statement below I had used before to focus on 1st element in a form, and it works very well.
$('form:first *:input[type!=hidden]:first').focus();
But now the problem is when I use it in a form that was empty(without any input element), and I create the elements inside that form by using jQuery .html() after some work, it will not focus on any element.
This is my form:

<form id="edit_marks" method="post">
  <div id="display">
  </div>
</form>

This is my jQuery AJAX:

function getData()
{
    var Semester = $('#Semester').find(':selected').val();
    var StudentID = "<?php echo $_GET['id'];?>";
    $.ajax(
    {
        type: 'POST',
        url: 'ajax_get_report_for_edit.php', 
        data: {Semester:Semester, StudentID:StudentID},
        dataType: 'text',
        success: function(data)
        {
            $('#display').html(data);
        },
        error: function(ts)
        {
            alert("AJAX Error: \n" + ts.responseText);
        }
    });
}
getData();
$('form:first *:input[type!=hidden]:first').focus();

You are triggering the event before you are adding the form, so you need to trigger event after form get added. Add it inside ajax success. Since ajax is asynchronous it may complete at any time, so before completing it will return from the function.

function getData()
{
    var Semester = $('#Semester').find(':selected').val();
    var StudentID = "<?php echo $_GET['id'];?>";
    $.ajax(
    {
        type: 'POST',
        url: 'ajax_get_report_for_edit.php', 
        data: {Semester:Semester, StudentID:StudentID},
        dataType: 'text',
        success: function(data)
        {
            $('#display').html(data);
            $('form:first *:input[type!=hidden]:first').focus();
        },
        error: function(ts)
        {
            alert("AJAX Error: \n" + ts.responseText);
        }
    });
}
getData();

Move the focus code inside the AJAX success, because AJAX means it is asynchronous call. So in order to make focus work after AJAX is to add it in the success.

function getData() {
    var Semester = $('#Semester').find(':selected').val();
    var StudentID = "<?php echo $_GET['id'];?>";
    $.ajax({
        type: 'POST',
        url: 'ajax_get_report_for_edit.php', 
        data: {
            Semester:Semester, 
            StudentID:StudentID
        },
        dataType: 'text',
        success: function(data) {
            $('#display').html(data);
            $('form:first *:input[type!=hidden]:first').focus();
        },
        error: function(ts) {
            alert("AJAX Error: \n" + ts.responseText);
        }
    });
}
getData();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM