Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

How to delete jQuery autocomplete item

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...