jQuery remove options from select

Viewed 558660

I have a page with 5 selects that all have a class name 'ct'. I need to remove the option with a value of 'X' from each select while running an onclick event. My code is:

$(".ct").each(function() {
    $(this).find('X').remove();
   });

Where am I going wrong?

12 Answers

If no id or class were available for the option values, one can remove all the values from dropdown as below

$(this).find('select').find('option[value]').remove();

Iterating a list and removing multiple items using a find. Response contains an array of integers. $('#OneSelectList') is a select list.

$.ajax({
    url: "Controller/Action",
    type: "GET",
    success: function (response) {
        // Take out excluded years.
        $.each(response, function (j, responseYear) {
            $('#OneSelectList').find('[value="' + responseYear + '"]').remove();
        });
    },
    error: function (response) {
        console.log("Error");
    }
});

Something that has quickly become my favorite thing to do with removing an option is not to remove it at all. This method is beneficial for those who want to remove the option but might want to re-add it later, and make sure that it's added back in the correct order.

First, I actually disable that option.

$("#mySelect").change(
    function() {

        $("#mySelect").children('option[value="' + $(this).val() + '"]').prop("disabled", true);

        $("#re-addOption").click(
            function() {
                $("#mySelect").children('option[value="' + howeverYouStoredTheValueHere + '"]').prop("disabled", false);
            }
        );
    }
);

and then to clean up, in my CSS, I set disabled options to be hidden, because hiding an option in some browsers doesn't work, but using the method above, clients with those browsers wont be able to select the option again.

select option[disabled] {
    display: none;
}

Personally, on the re-addOption element, I have a custom property of data-target="value", and in place of howeverYouStoredTheValueHere, I use $(this).attr('data-target').

When I did just a remove the option remained in the ddl on the view, but was gone in the html (if u inspect the page)

$("#ddlSelectList option[value='2']").remove(); //removes the option with value = 2
$('#ddlSelectList').val('').trigger('chosen:updated'); //refreshes the drop down list

I tried this code:

$("#select-list").empty()

Try this for remove the selected

$('#btn-remove').click(function () {
    $('.ct option:selected').each(function () {
        $(this).remove();
    });
});
Related