Matthew Matthew - 2 years ago 67
Javascript Question

Remove option from selected list based of index?

I have two select lists and based off the selected index of either one I need to remove the option at that index from both lists.

I have seen example of doing this for the currently selected option using the

function but that would only work for one list as the other list might have a different option selected or none at all.

Knowing just the index value is it possible to do this with JavaScript / jQuery? I already have the code that figures out which list to pull the index from and get that index value. I just have not found a way to specify an index value for the removal.

Code developed based off comment:

function RemoveCode(codeType)
var selectedProjectsField = $("#SelectedProjects");
var selectedProjectCodesField = $("#SelectedProjectCodes");
var selectedTasksField = $("#SelectedTasks");
var selectedTaskCodesField = $("#SelectedTaskCodes");
var selectedOptionIndex;

if (codeType == "Project")
selectedOptionIndex = $("#SelectedProjects :selected").index();
selectedOptionIndex = $("#SelectedTasks :selected").index();



Answer Source

Using The :eq() Selector

You could use the :eq() selector to target a specific element by it's index and then call remove() to remove it from the DOM :

// Syntax Example: This will remove then (index)th option element 
$('select option:eq(index)').remove();

So in your case, you would simply want to concatenate your selectedOptionIndex into the selector to target selector using one of the following :

// Remove a specific option of your SelectedProjects element
$('#SelectedProjects option:eq(' + selectedOptionIndex + ')').remove();


You can see an interactive example here and demonstrated below :

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download