I have a code that removes an option element from a select multiple(<select multiple></select>) tag when the option is clicked.
The code works +- like this.
var option = new Option("sometext","someval");
$(option).click( function(){
selectBox.remove(option);
return false;
}
);
$(selectBox).append(option);
It works very well on all engines I can remember (gecko, presto, webkit…) except IE.
According to my research, IE does not support adding events to option tags so I added the event to the select tag.
$(selectBox).click( function(event){
if (option === selectBox.options[selectBox.selectedIndex]) {
event.preventDefault();
event.stopPropagation();
selectBox.remove(option);
return false;
}
event.preventDefault();
return true;
}
);
Where is: if (option === selectBox.options[selectBox.selectedIndex]) {
I already tried: if ($(option).is(':selected')) {
Didn’t work either.
What happens:
When I click an option all binded functions are activated and there can be activated functions after the element is deleted.
Using event.stopPropagation(); (propagation does continue, anyway) seem not to be doing what I want as all other events are also called.
Changing the event from click to change does not solve the problem because when the selected option is changed it is deleted and then the selected option becomes another one causing the event to be called again and, in the end, all elements in the select are deleted.
Try this code; Assume
selectBoxto be a DOM element, a JQuery object, or a CSS selector which points to the<select>element:The selected option is referred through the
selectedIndexproperty of the element. When each option is looped through, the selected option will -at a certain point- be found. When this element is found, the option is removed, and the loop breaks usingreturn false.Instead of using
.click, I recommend using.change, so that selection changes through the keyboard (arrow keys + tab) is also dealt with.