Rodrigo Porcionato
Rodrigo Porcionato

Reputation: 155

How to update/refresh DOM item after insert jQuery

I try to figure out how to update the element LI after use insertBefore function jQuery.

The problem is after add any new elements to UL, I can not delete the element same,(with emailTagRemove).

See the demo to see the problem: http://jsfiddle.net/HsRfH/

<div class="content"> 
    <span class="">Please, insert one or more emails: </span> 
    <br />
    <ul id="ulEmailsCotacao" class="ulEmailsCotacao">
        <li class="liEmailTagNew">
            <input type="text" class="emailInputTag" name="" value="" />
        </li>
    </ul>
</div>

  //if enter, tab or space, add new value
  $('.emailInputTag').keydown(function (e) {
      var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
      if (key === 13 || key === 9 || key === 32) {
          addEmail();
      }
  });

  addEmail = function () {
      var email = $('.emailInputTag').val().trim();
      $('<li class="liEmailTagChoiced">' + email + '<a id="del" class="emailTagRemove">x</a></li>').insertBefore('.liEmailTagNew');
      $('.emailInputTag').val("");
  };

  $('.emailTagRemove').click(function () {
      var email = $(this).parents("li");
      email.remove();
  });

Upvotes: 6

Views: 37530

Answers (2)

Praveen
Praveen

Reputation: 56519

Because those are dynamically added elements to the existing HTML, so you need to delegate it using on event handler attachment with the document.

$(document).on('click','.emailTagRemove', function () {                
                var email = $(this).parents("li");
                email.remove();
            });

JSFiddle

As @null pointed using the static selector instead of document is good, in order to avoid conflict among those elements in entire code.

$('#ulEmailsCotacao').on('click','.emailTagRemove', function () {                
                var email = $(this).parents("li");
                email.remove();
            });

JSFiddle

Upvotes: 0

dsgriffin
dsgriffin

Reputation: 68616

You'd need to use event delegation for this, due to the elements being added/removed dynamically:

 $('.content').on('click', '.emailTagRemove', function () {                
      var email = $(this).parents("li");
      email.remove();
 });

Use .content as the selector as it's more efficient than using document in this case.

jsFiddle here

Upvotes: 15

Related Questions