'How can I remove a select option with the ability to re-insert it using jQuery?
So I will have 2 identical dropdowns FromJob and ToJob. I need to remove the item from the 2nd dropdown that was selected in the first dropdown. The caveat is if the user changes their mind in the 1st dropdown, then I need to put that value back in, and remove the new value selected.
I thought I would use ajax and clear the 2nd dropdown, then add all values to the 2nd dropdown, and finally then remove the value that was selected in the first, that way the 2nd dropdown will always have all values except for the one selected in the first dropdown.
$(function () {
$('#FromJob').change(function () {
var fromId = $('#FromJob').val();
$.ajax({
url: '/Patterns/PopulateJobs',
type: 'GET',
dataType: 'json',
data: {},
success: function (response) {
alert(fromId);
var len = response.length;
$('#ToJob').empty();
$('#ToJob').append('<option value="">Make Selection</option>');
for (var i = 0; i < len; i++) {
var id = response[i]['JobId'];
var text = response[i]['JobTitle'];
$('#ToJob').append('<option value="' + id + '">' + text + '</option>');
}
}
});
$("#ToJob option[value='" + fromId + "']").remove();
});
});
Unfortunately that did not work. I also tried to not add the selected item like so
$(function () {
$('#FromJob').change(function () {
var fromId = $('#FromJob').val();
$.ajax({
url: '/Patterns/PopulateJobs',
type: 'GET',
dataType: 'json',
data: {},
success: function (response) {
alert(fromId);
var len = response.length;
$('#ToJob').empty();
$('#ToJob').append('<option value="">Make Selection</option>');
for (var i = 0; i < len; i++) {
var id = response[i]['JobId'];
var text = response[i]['JobTitle'];
if (response[i]['JobId'] != fromId) {
$('#ToJob').append('<option value="' + id + '">' + text + '</option>');
}
}
}
});
});
});
That also did not work.
Solution 1:[1]
I inspected the response returned from the AJAX call and found that I had called it JobId in the AJAX and it was actually JobID. So the value in each option was showing as undefined and that was why neither option above worked. I fixed that and both options work.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
