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 remove()
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();
}
else
{
selectedOptionIndex = $("#SelectedTasks :selected").index();
}
alert(selectedOptionIndex);
selectedProjectsField.eq(selectedOptionIndex).remove();
selectedTasksField.eq(selectedOptionIndex).remove();
}
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();
Example
You can see an interactive example here and demonstrated below :
This code should work:
$('#SelectedProjects option')[index].remove();
$('#SelectedTasks option')[index].remove();
or
selectedProjectsField.find('option')[selectedOptionIndex].remove();
selectedTasksField.find('option')[selectedOptionIndex].remove();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.