NtnRanger NtnRanger - 6 months ago 84
Javascript Question

jQuery $.focus() not working with id and with input type

I have a little problem:

I have a modal that opens after some result search with ajax: it opens and show all requested results correctly.

On close, I need to empty another div with ID "results", empty an input with ID "search" and focus on it:


  • empty "results" is working

  • changing value of "search" to "" is also working

  • focus on "search" is not working



Here's my HTML:

<div class="col-sm-3">
<form action="" method="post" id="searchit">
<div class="input-group mar-btm">
<span class="input-group-addon"><i class="fa fa-search fa-lg"></i> Ricerca:</span>
<input type="text" id="search" tabindex="1" class="form-control" name="search" placeholder="Codice, EAN o Testo" />
</div>
</form>
</div>
<div class="col-sm-4" id="results"></div>


UPDATE:
jQuery:

$(".modal").on('hidden.bs.modal', function () {
$("#results").empty();
$("#search").val('');
$("#search").focus();
});


I also tried:

$(".modal").on('hidden.bs.modal', function () {
$("#results").empty();
$("#search").val('').focus();
});


and (is the only text input on this page):

$(".modal").on('hidden.bs.modal', function () {
$("#results").empty();
$("#search").val('');
$('input[type="text"]').focus();
});


In every case, empty() and val() are working properly but nothing is working with focus()! No error thrown in console...

I can't figure out what I'm missing/doing wrong!

Some help? Thanks in advance!

Answer

Problems with trying to use .focus() in an event handler usually stem from the event being handled also having an affect on focus. To get around that, I usually just wrap the .focus() call in a timeout:

$(".modal").on('hidden.bs.modal', function () {
     $("#results").empty();
     $("#searc").val('');
     setTimeout(function() {
       $("#searc").focus();
     }, 10);
});

The timeout handler will run basically immediately after whatever triggered the event handler is all finished.

Comments