user478636
user478636

Reputation: 3424

Set focus on textbox in jQuery

I've made a textbox, and when the user types in a command. That command is passed to a php file using jquery-ajax and executed on the server, and the results are returned. These results are output on the browser by creating div tag.

The problem is that I'm appending the div tag. As I'm appending, my textbox seems be going out of focus, I have to scroll down the page to be able to see what I'm typing.

This is the function that receives the command I type in the textbox.

$(function() {
    $('#cmd').keydown(

    function(event) {
        if (event.keyCode == 13) {
            event.preventDefault(); /*you can call your function here*/
            var tmp = $(this).val();
            $('#cmd').val('');
            commands.push(tmp);

            MyFunction(tmp);
            /*still you can it here*/
        }
    });
});

This function receives the returned value, and creates the div tag.

function MyFunction(msg) {
    var cmdStr = msg;
    $.ajax({
        url: 'exec.php',
        dataType: 'text',
        data: {
            q: cmdStr
        },
        success: function(response) { 

    $('#output').append("<div class=type> www-data@ubuntu:~# " + cmdStr +"</div>" + "<div class=output>" + response + "</div>");
        }

    });

}

Upvotes: 5

Views: 29409

Answers (2)

mattsven
mattsven

Reputation: 23303

Try this:

success: function(response){
    $("#output").append("<div class=type> www-data@ubuntu:~# " + cmdStr +"</div>" + "<div class=output>" + response + "</div>");
    $("#cmd").focus(); //Wil focus your textbox
}

Upvotes: 16

Rory McCrossan
Rory McCrossan

Reputation: 337714

Try this:

$(function() {
    $('#cmd').keydown(

    function(event) {
        if (event.keyCode == 13) {
            event.preventDefault(); /*you can call your function here*/
            var tmp = $(this).val();
            $('#cmd').val('');
            commands.push(tmp);

            MyFunction(tmp);
            $(this).focus(); // Set the focus back on to the #cmd element
        }
    });
});

Upvotes: 3

Related Questions