Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>");
        }

    });

}
like image 948
user478636 Avatar asked Apr 24 '11 18:04

user478636


2 Answers

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
}
like image 108
mattsven Avatar answered Sep 28 '22 01:09

mattsven


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
        }
    });
});
like image 20
Rory McCrossan Avatar answered Sep 27 '22 23:09

Rory McCrossan