0

I use jquery to add tag dynamically, but I face some problems. I can remove the tags in original code, however, I can't remove the tag which is added by jquery.

Another question is how could I avoid adding duplicated tag (same value)? Many thanks!

<div id='searchTerm' class='searchTerm'>
    <span><b>U.S.A</b><a class="remove" href="#"></a></span>
    <span><b>H.K.</b><a class="remove" href="#"></a></span>
</div>

$('document').ready(function(){
    $('#addTag').click(function() {
        var html='';
        html += '<span><b>' + $("#newTag").val() + '</b><a class="remove" href="#"></a></span>';
        $('#searchTerm').append(html);
    });
    $('.remove').click(function() {
        $(this).parent().remove();
    });
}); 

1 Answer 1

1

use on() for the tags added dynamically

$(document).on('click','.remove',function() {
    $(this).parent().remove();
});
Sign up to request clarification or add additional context in comments.

6 Comments

@Eric, .click() will simply apply the click event for the items found in DOM at the time of loading. They will not be invoked for dynamically added elements. However, with on() you can attach the click event at the document level but with a specific selectors.
But if I use $('.remove').on('click', function({$(this).parent().remove();}); to implement the event, the new tags could not be deleted. So the reason might be using $(document)?
@Eric, basically $(document) you are asking a document to take care of listening for .remove selectors. In your code, you are asking the current .remove elements to take care. But they will not take care of the dynamic items
I got it! Thank you for kindly reply! Have a nice day :)
Do you have any suggestion about how to avoid adding duplicated tag?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.