Jquery new line after press enter

I would like to add a new line after press enter. My code can add only 1 time. Please, help.

$(function () {
  $('.items:last .item-quantity').keypress(function(e) {
    var keyCode, path, duplicate;

    keyCode = e.keyCode || e.which;
    if(keyCode == '13') {
      path = '.items:last';
      duplicate = $(path).clone();
      duplicate.children().val(null);
      $(path).after(duplicate);
      $(path + ' .item-name').focus();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-xs-12 items">
  <input type="text" class="form-control item-name col-xs-2" placeholder="Name">
  <input type="text" class="form-control item-quantity col-xs-2" placeholder="Quantity">
</div>

Answers 1

  • The problem is that you are only attaching the keypress event listener to the last input element when the page loads. You could delegate the event handler to a common ancestor element in order to listen to the event on the newly appended elements:

    $(document).on('keypress', '.items:last .item-quantity', function(event) {
      var keyCode = event.keyCode || event.which;
      var path = '.items:last';
      var $duplicate = $(path).clone();
    
      if (keyCode === 13) {
        $duplicate.children().val('');
        $(path).after($duplicate);
        $('.item-name', path).focus();
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="col-xs-12 items">
      <input type="text" class="form-control item-name col-xs-2" placeholder="Name">
      <input type="text" class="form-control item-quantity col-xs-2" placeholder="Quantity">
    </div>

    In the snippet above, the event listener is delegated to the document object. This means that a check is made for all the keypress events that propagate up the document object. Therefore it would be more efficient if you can attach the event listener directly to to a common ancestor.

    For instance:

    $('.parent-container').on('keypress', '.items:last .item-quantity', function(event) {
      var keyCode = event.keyCode || event.which;
      var path = '.items:last';
      var $duplicate = $(path).clone();
    
      if (keyCode === 13) {
        $duplicate.find('input').val('');
        $(path).after($duplicate);
        $('.item-name', path).focus();
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="parent-container">
      <div class="col-xs-12 items">
        <input type="text" class="form-control item-name col-xs-2" placeholder="Name">
        <input type="text" class="form-control item-quantity col-xs-2" placeholder="Quantity">
      </div>
    </div>


Related Articles