Reset select value to default

前端 未结 23 1583
暗喜
暗喜 2020-11-27 03:52

I have select box


                        
    
提交评论

  • 2020-11-27 04:11

    If using Spring forms, you may need to reset the selected to your options label. You would set your form:select id value to an empty string resets your selection to the label as the default.

    <form:select path="myBeanAttribute" id="my_select">
        <form:option value="" label="--Select One--"/>
        <form:options items="${mySelectionValueList}"/>
    </form:select>
    
     $("#reset").on("click", function () {
            $("#my_select").val("");
     });
    

    in the case where there's a reset button. Otherwise

    $("#my_select").val("");
    
    0 讨论(0)
  • 2020-11-27 04:12

    I was trying to resolve it like the other answers unfortunately, I didn't get a right way to do it, once I tried as I write below:

    $('#<%=ddID.ClientID %>').get(0).selectedIndex = 0;
    

    this code works for me, I hope that will be useful for you guys.

    Best Regards.

    Samuel Alvarado.

    0 讨论(0)
  • 2020-11-27 04:14

    For those who are working with Bootstrap-select, you might want to use this:

    $('#mySelect').selectpicker('render');
    
    0 讨论(0)
  • 2020-11-27 04:14
    $('#my_select').find('option:not(:first)').remove();
    

    Call this function each time before populating the select

    0 讨论(0)
  • 2020-11-27 04:19

    You can make use of the defaultSelected property of an option element:

    Contains the initial value of the selected HTML attribute, indicating whether the option is selected by default or not.

    So, the DOM interface already keeps track which option was selected initially.

    $("#reset").on("click", function () {
        $('#my_select option').prop('selected', function() {
            return this.defaultSelected;
        });
    });
    

    DEMO

    This would even work for multi-select elements.

    If you don't want to iterate over all options, but "break" after you found the originally selected one, you can use .each instead:

    $('#my_select option').each(function () {
        if (this.defaultSelected) {
            this.selected = true;
            return false;
        }
    });
    

    Without jQuery:

    var options = document.querySelectorAll('#my_select option');
    for (var i = 0, l = options.length; i < l; i++) {
        options[i].selected = options[i].defaultSelected;
    }
    
    0 讨论(0)
  • 提交回复
    热议问题