I\'m trying to empty select options when:
id \"mClick\" is selected, id\'s \"sClick\", \"cClick\" and \"srClick\" will be emptied.
id \"sClick\" is selected,
It's Work
$('#mClick').change(function () {
$('#sClick, #cClick, #srClick').find("option:gt(0)").remove();
});
$('#sClick').change(function () {
$('#cClick, #srClick').find("option:gt(0)").remove();
});
$('#cClick').change(function () {
$('#srClick').find("option:gt(0)").remove();
});
you can use the greater than :gt()
selector of jQuery for this
$('#lForm select[id!="makeClick"] select[id!="stateClick"] select[id!="cityClick"] option:gt(0)').remove().end();
This will remove all options that are greater than 0
The easiest way to clear the options in the way you're describing is by using options.length = 1
. Also, you can leverage the fact that each drop down clears the ones that logically follow it, so that you only need to declare a single change handler.
$('#lForm select').on('change', function() {
if (this.selectedIndex > 0) {
var $others = $(this).closest('table').find('select'),
current = $others.index(this); // find current
while (++current < $others.length) {
// for each following drop down
$others.get(current).options.length = 1;
}
}
});
Demo
I'm not sure how you're going to repopulate the drop downs though :)
I was looking for one line code, what I found after lots of research is the Simplest and Best one line code to remove everything except first.
JQuery,
$('#ddlId option:not(:first)').remove();
Try this
$('#lForm select').change(function(){
var $selects = $('#lForm select');
var idx = $selects.index(this);
// Use `val` function to clear the selected values or Use `remove` function to remove the element.
$selects.filter(':gt(' + idx +')').val('');
});
Try this
yourSelect.find('option').not(':first').remove();