How do I prevent the input-text focus from being lost when I click on another element?

1

I have input of type text , where I can enter a search, which is executed via ajax, as the user types. Below this I have a list of items that were found in table . When I click on this table, I change the style of the row clicked, as if it was selected, but I do not want the focus of the input to be lost ... I want the user, even after clicking the table, to continue typing. >

I have tried the blur event but so far I still can not, because I do not know if the clicked element was inside the table.

    
asked by anonymous 13.02.2014 / 14:15

4 answers

3

You can put an event in the table to return focus to the search field with the focus() function of jQuery.

Example

//evento click da tabela
$('#resultado').on('click', 'tr', function() {

    //muda a cor da linha atual
    $(this).css('background-color', '#DDEEFF')

    //tira a cor das outras linhas
    $(this).siblings().css('background-color', 'transparent')

    //devolve o foco ao campo de pesquisa
    $('#pesquisa').focus();

});

Demo on jsfiddle

    
13.02.2014 / 14:31
2

If you click on another element, you will lose the focus of the text box. This is controlled by the browser.

The maximum you can do is to use the click event of the table row (or whichever event you already use to change the row style) to call the focus method to return the focus to the box of text. But remember, there will be a focus change, however fast, and the focus events and blur will be fired to the box and to the table row.

    
13.02.2014 / 14:18
2

I've solved the problem, but this is one of those that should tune the browser-by-browser tips, since each one has a different thing ... so, having said that, here's a solution I was able to test on Chrome 32, Firefox 27 and in IE 8.

The basic idea is in the event blur of the input, set the focus to itself, if the element clicked belongs to the table.

Reaching the final solution

  • First, the table must have tabindex , otherwise some browsers can not see where the focus is going. e.g. Chrome

  • Then I have to know where the focus is going, each browser in its own way:

    • explicitOriginalTarget in Chrome;

  • When I focus on relatedTarget I discovered it does not work in FF, so I had to use a blur

  • the focus back to the input.

Solution Fiddle


References / Research Material

13.02.2014 / 23:03
1

Answer:

There's no way to avoid this.

Because of browser default behavior, if you click something else, your focus is lost, but you can return the focus using like this:

$('sua_tabela tr').click(function(){
  $('seu_input').focus();
});

You can simply $('seu_input').focus(); at the end of the code you have to select that row of the table, but make sure focus() is running at the end of the process.

    
13.02.2014 / 14:24