Reputation: 658
Working with jQuery, I'm trying to do a .focus() on an input field after a AJAX call, but with no luck so far.
Little snippet to give the idea:
$.ajax({
type: "GET",
url: url,
success: function (data) {
$('#myModal').remove();
$('body').append(data);
$('#myModal').modal('show');
},
complete: function(){
$('#input-new-saldo').focus();
}
});
Here's the HTML: (loaded by AJAX and appended to body)
<form id="form-update-saldo">
<div class="modal-body">
<div class="form-group">
<label class="sr-only" for="input-new-saldo">Saldo (in euro)</label>
<div class="input-group">
<input type="text" class="form-control input-lg" id="input-new-saldo" name="new_saldo" value="<?php echo $saldo['saldo']; ?>">
<div class="input-group-addon">€</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success" id="submit-update-saldo">Update saldo</button>
</div>
</form>
What I have tried so far:
However, calling $('#input-new-saldo').focus(); does nothing, nor gives any JS error.
To me it seems the focus is somehow lost during the AJAX call to somewhere outside my application and I'm not able to steal it back in the callback function. Would that make sense and how could it possible be solved?
Upvotes: 0
Views: 4460
Reputation: 658
Odd enough, found ultimately this thread https://stackoverflow.com/a/23921617/3963594 which addressed the issue directly.
The important part was to bind the event to the modal after appending it to body, before showing it.
Upvotes: 1
Reputation: 153
$.ajax({
type: "GET",
url: url,
success: function (data) {
$('#myModal').remove();
$('body').append(data);
$('#myModal').modal('show');
$('#myModal').on('shown', function() {
$('#input-new-saldo').focus();
});
}
});
Upvotes: 0
Reputation: 3291
You're are pretty close . Input elements can have an autofocus attribute .
So instead of :
$('#input-new-saldo').focus();
Try :
$('#input-new-saldo').attr('autofocus' , 'true');
Hope this helps
Upvotes: 0