Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Focus an input field after appending with jQuery

I want to append an input field on click, and focus it so that it has a blinking cursor and can be typed directly. With the following code I am able to append it but i doesn’t focus. I first need to click on the field and then I can type.

How can I append and focus?

I have tried following line but it doesn’t do anything

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$('.fields').append(field_html).focus();

HTML:

<div class="fields">
<!-- append here -->
</div>    

<div class="row">
<input name="input" class="input">
</div>

<button>Add</button>

JS:

$('button').on('click', function(e){
  var field_html = $('.row').html();    
  $('.fields').append(field_html);
});

CSS:

.input{
  padding: 10px 10px;
  border: 1px solid blue;
  width: 300px;
  margin-bottom: 10px;
}

.row {
  display: none;
}

JSFiddle:
https://jsfiddle.net/sLob7cwh/

>Solution :

this code works and will add focus to the latest added input

$('button').on('click', function(e){
  var field_html = $('.row').html();    
  $('.fields').append(field_html).find('input:last').focus();
});

fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading