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
$('.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();
});