Jay.
Jay.

Reputation: 331

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

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

 $('button').on('click', function(e){
      var field_html = $('.row').html();    
      $('.fields').append(field_html);
    });
 .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 class="fields">
    <!-- append here -->
    </div>    
    
    <div class="row">
    <input name="input" class="input">
    </div>
    
    <button>Add</button>

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

Upvotes: 0

Views: 762

Answers (2)

john Smith
john Smith

Reputation: 17906

$('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 class="fields">
<!-- append here -->
</div>    

<div class="row">
<input name="input" class="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();
});

fiddle

Upvotes: 1

fdomn-m
fdomn-m

Reputation: 28611

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

Upvotes: 1

Related Questions