I have an function where I have some drop-downs.
I have some values where I have to check whether the values exist in the dropdown.
If they exist I have to keep them and remove other options from my dropdown
This is what I have been trying to do
function getimage(value, ProdId) {
$.getJSON("/api/ProductDetails", { option: value, productid: ProdId }, function (data) {
$.each(data, function (idx, product) {
$('#defaultimage').empty();
$('<img id="dfltimage"/>').attr({ src: product.ImageURL }).appendTo('#defaultimage');
if (product.options.length > 0) {
$.each(product.options, function (idx, option) {
/*appending the each option to a label*/
$("" + "#" + option.OptionName + "").empty();
if (option.values.length > 0) {
/*Creating a select tag for the Retrieved options*/
//$("" + "#" + options.OptionName + "").empty();
$.each(option.values, function (idx, value) {
alert(value.OptionValue);
// $("" + "#" + option.OptionName + "").append('<option value="' + value.OptionValue + '">' + value.OptionValue + '</option>');
$("" + "#" + option.OptionName + "").children('option').hide();
// $("" + "#" + option.OptionName + "").children("option[text=" + value.OptionValue + "]").show();
$("" + "#" + option.OptionName + "option[value='" + value.OptionValue + "']").show();
});
}
})
}
});
});
}
in this case dropdowns are empty in the end
this is what the changes i made from the answer given
if (product.options.length > 0) {
$.each(product.options, function (idx, option) {
/*appending the each option to a label*/
$("" + "#" + option.OptionName + " option").attr('not_required', 'true');
if (option.values.length > 0) {
/*Creating a select tag for the Retrieved options*/
$.each(option.values, function (idx, value) {
alert(value.OptionValue);
$("" + "#" + option.OptionName + "option[value='" + this_value + "']").removeAttr('not_required');
$("" + "#" + option.OptionName + " option[not_required=true]").remove();
});
}
})
}
the values are not removed
Start by setting an attribute in all options, e.g. “not_required”.
Then loop through your results, removing the attribute for each one as you find it.
Finally select all options which still have the attribute and remove (or hide) them.
[Edit]
You are removing the ‘unwanted’ options too soon. You need to wait until the loop finishes.
This is my version of your edit above: