How to set focus using jQuery on an element that has just appeared
Asked Answered
A

2

8

I have a document ready block as follows:

$(document).ready(function () {
    $('#addTagLink').click(function () {
        $('#addTagField').show();
        $('#addTagField').val("");
        $('#addTagField').focus();
    });
});

The addTagField is a regular text input that has display:none set by css on page load.

When a user clicks on the addTagLink element the input field is shown correctly but focus doesn't get set to the field as intended.

I figured it must be something to do with the display:none / show() functionality, so changed the $('#addTagField').focus(); to another field $('#name').focus();which worked perfectly.

Can anyone suggest firstly why I see this issue and secondly, how to fix it?

Afroamerican answered 17/2, 2012 at 12:1 Comment(3)
It works just fine in this fiddle - click the show text to show the input and set focus to it.Pharisaic
Thanks Christofer - I found the issue, a mistake in wrong ids! :/Afroamerican
you can try this $('input:text:first').focus();Semela
A
6

Turns out it was a problem with my element IDs. Oops.

Afroamerican answered 27/7, 2012 at 10:29 Comment(0)
D
11
// Variable to store element
var btn = document.querySelector( ".btn-primary");

// Click Event
$(btn).click(function() {

  // Jquery to define which element will get focus
  $(".form-control").focus();

});
Dinette answered 19/7, 2018 at 15:53 Comment(1)
While this code may answer the question, it is better to include the essential parts of the answer here and provide the code for reference.Geronimo
A
6

Turns out it was a problem with my element IDs. Oops.

Afroamerican answered 27/7, 2012 at 10:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.