Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

My JQuery code is:

$(function() {
$( document ).tooltip({
  track: true
});
});
$(document).ready(function() {
  $(function() {
var availableTags = ["Bangladesh","USA","Uk","CANADA","Angola","Antigua and  Barbuda","Argentina"];
var country;
$( "#country_name" ).autocomplete({
  source: availableTags,
  autoFocus: true,
  select: function( event, ui ) {              
       country=ui.item.value;  //$('#target').text( ui.item.value );
       //$('#div_selected_country').text($('#div_selected_country').html()+"
 "+country);
       $('#div_selected_country').html($('#div_selected_country').html()+"<span>"+country+
            " <a href='?delete=1' class='del_country'>X</a></span>"+"
 ");
       $('#hid_country_names').val($('#div_selected_country').html());
       if ( ui.item ){
          $(this).val('');
          return false;
       }
  }
});
  });
});
$(document).ready(function() {
//$('a.del_country').click(function(e) {
$('a.del_country').on('click', function() { //.on in JQuery 1.9 and up instead of .live
    alert('sumon');
});
});

Here is the JSFiddle here

I am trying to implement auto complete for list of countries, add one by one and shows into another div. Up to this point my code works fine, but I need to remove selected countries as well (one by one).

What I have done, when I add a country I include a span tag by mentioning a class; and later when I try to access that class using jQuery, I failed to get that class.

From my understanding, my span tag is not binding properly with HTML DOM and that's why later it's not identified.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
226 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need to use event delegation approach for .on() since the elements with class="del_country" are being added dynamically.

$(document).on('click','a.del_country', function(e) { 
        e.preventDefault();/* prevent browser opening href url*/
        /* remove parent span*/
        $(this).parent().remove();
});

DEMO


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...