Search code examples
jquerydrop-down-menu

Remove values from DropDownList


$("#Month option:selected").val()

this is giving me a selected value from my dropdownlist. But i want to remove or hide some options in my dropdownlist can i do with the help of this?

$("Day option").value("31").empty();

is it valid or not. Please give me solution.

    function ValidatefuneralDate() {
    var today;
    var currentDate = new Date();
    var year = currentDate.getFullYear();
    var month = currentDate.getMonth() + 1;  
    var day = currentDate.getDate();
    if (window.location.href.indexOf("en-US") > -1) 
    {
        today = month + '/' + day + '/' + year;
        var selectedDate = $("#Month option:selected").val() 
        +'/'+$("#Day option:selected").text() + '/' + 
        $("#Year option:selected").text();
    }
    else 
   {
        today = day + '/' + month + '/' + year;
        var selectedDate = $("#Day option:selected").
        text() + '/' +   $("#Month option:selected").
        val() + '/' + $("#Year option:selected").text();
    }
    if ($("#Month option:selected").val("2"))
    {
        $("#Month option[text='31']").hide();
        $("#Month option[text='30']").hide();
        $("#Month option[text='29']").hide();
    }
    if (selectedDate < today) {
        $("#lblFeneralDate").html('@Html.
        R(VirtualPath, "ValidatefuneralDate")');
        return false;
    }
    else { return true;}
   }

This is my jquery function and

<div class="DDLabel">
Day:@Html.DropDownList("Day", new SelectList(new List<object>
{
                                        new { value =1, text = "1"},
                                        new { value =2, text = "2"},
                                        new { value =3 ,text ="3"},
                                        new { value =4, text = "4"},
                                        new { value =5, text = "5"},
                                        new { value =6, text = "6"},
                                        new { value =7, text = "7"},
                                        new { value =8, text = "8"},
                                        new { value =9, text = "9"},
                                        new { value =10, text = "10"},
                                        new { value =11, text = "11"},
}, "value", "text", 1), 
new { @onchange = "e_date_changed();", @style ="width:66px" })

This is DDL for days from 1 to 31 like this.


Solution

  • You can use .remove() to completely remove element from DOM.

    $("#Month option[value='whatever']").remove();
    

    EDIT

    $("#Month option[value='whatever']").hide();
    

    and you can later get them back by

    $("#Month option[value='whatever']").show();