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 >
<!-- append here -->
</div>
<div >
<input name="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/
CodePudding user response:
$('button').on('click', function(e){
var field_html = $('.row').html();
$('.fields').append(field_html).find('input:last').focus();
});
.input{
padding: 10px 10px;
border: 1px solid blue;
width: 300px;
margin-bottom: 10px;
}
.row {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<!-- append here -->
</div>
<div >
<input name="input" >
</div>
<button>Add</button>
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();
});
CodePudding user response:
JQuery methods generally chain the collections, in the case of .append it passes through the original collection.
Instead, you can use .appendTo which passes through the new html (as it's the original collection)
Change
var container = $("container").append("new_html");
to
var newElements = $("new_html").appendTo("container");
You can then use that result going forward, so your code becomes:
$('button').on('click', function(e){
var field_html = $('.row').html();
$(field_html).appendTo(".fields").find("input.input").focus();
});
