Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
  });
like image 836
Rodrigo Porcionato Avatar asked Apr 04 '14 22:04

Rodrigo Porcionato


People also ask

How do you refresh a DOM element?

The location reload() method in HTML DOM is used to reload the current document. This method refreshes the current documents. It is similar to the refresh button in the browser.

How to append after in jQuery?

jQuery insertAfter() MethodThe insertAfter() method inserts HTML elements after the selected elements. Tip: To insert HTML elements before the selected elements, use the insertBefore() method.

How to use replaceWith in jQuery?

The replaceWith() method in jQuery is used to replace the selected elements with the new one. This method replaces the matched elements with the specified HTML elements. It returns the replaced elements. This method is similar to the replaceAll() method.


1 Answers

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

like image 178
dsgriffin Avatar answered Nov 08 '22 13:11

dsgriffin