I am generating an output of options selected from drop down list.
I want to allow the user to 'remove' selections from the output.
I can't get my code to work though, here is the code which renders the output:
$('#dataCombo').change(function(){
$('#dataOutput').html('');
var values = $('#dataCombo').val();
for(var i = 0; i < values.length; i += 1) {
$('#dataOutput').append(values[i] + 'X
'+'
')
}});
So the selected drop down item is displayed on the page with a 'X' next to it in P tags with the class "removable", generated. I've inspected this in chrome and the p tag is created with the correct class.
I added this code to remove the clicked option however it doesnt work:
$('.removeable').click(function(){
$('.removeable').remove();
console.log("I did this");
});
The item doesn't get removed, i don't get a log in the console. Any idea why this wouldnt work?
EDIT:
I've amended my code to this:
$('#dataOutput').append('' + values[i] + 'X
'+'
')
And it does indeed remove the item, however the option is still 'selected' in the drop down box. I was trying to get it to 'unselect' this as well. I'm using Bootstrap and a drop down with 'multiple' activated. While the option is currently removed from the output, it's not removed from the select box (meaning when another option is clicked it re-renders the previously removed element).
I've asked the question (hopefully) more clearly, in a different way to the duplicated question:
Unselect an option using jQuery on a Bootstrap selectpicker
Answer
Use event delegation and please use $(this)
reference inside of that click handler, If you dont use that, then while clicking on a single element results in removing all those elements with that class
$("#dataOutput").on('click','.removeable',function(){
$(this).remove();
console.log("I did this");
});
And also note that, always prefer the closest static parent for delegating the events
No comments:
Post a Comment