Reset select value to default

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

I have select box


                        
    
提交评论

  • 2020-11-27 03:59

    With jquery :

    $("#reset").on("click", function() {
        $('#my_select').val($('#my_select').find('option[selected="selected"]').val());
    }
    
    0 讨论(0)
  • 2020-11-27 03:59

    Reset all selection fields to the default option, where the attribute selected is defined.

    $("#reset").on("click", function () {
        // Reset all selections fields to default option.
        $('select').each( function() {
            $(this).val( $(this).find("option[selected]").val() );
        });
    });
    
    0 讨论(0)
  • 2020-11-27 04:00

    This works for me:

    $("#reset").on("click", function () {
        $("#my_select option[selected]").prop('selected', true);
    }
    

    You find for the default option that has the select attribute and you change the selection to that option.

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

    Bind an event handler to the focus event of the select to capture the previous value. Then set the value of the select to the previous value when reset is clicked.

    var previousValue = "";
    $("#my_select").on("focus",function(){
        previousValue = $(this).val();
    });
    
    $("#reset").on("click", function () {
       $("#my_select").val(previousValue);
    });
    

    Working Example: http://jsfiddle.net/T8sCf/17/

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

    You can do this way:

    var preval = $('#my_select').val(); // get the def value
    
    $("#reset").on("click", function () {
       $('#my_select option[value*="' + preval + '"]').prop('selected', true);
    });
    

    checkout this fiddle

    take a var which holds the default loaded value before change event then get the option with the attribute selector of value with holds the var value set the property to selected.

    0 讨论(0)
  • 提交回复
    热议问题