简体   繁体   中英

how do I set the default value of a dropdown after it has been changed?

I have a dropdown on html page, when it is first loaded, it is set to a default value. But when a user changes the value, I want the ability to set the dropdown back to the original default value by clicking a button.

How can I achieve this? without keeping a copy of the original value in a hidden field.. its like how the javascript reset form function.. but I just want it to apply to just the drop down..

Thanks

considering you have a simple select box.. you can use val() to set the options..

<select id="selectId">
<option value="0">Default Value</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="button" id="buttonID" value="change"/>

try this

$('#buttonID').click(function(){
    $('#selectId').val('0'); //value of your default option
});

fiddle here

However, if you default option is disabled , then you would need a work around to make the assignment. a small bit like so:

$(document).on('click', '#buttonID', function(e) {
    var d = $('#selectId option:disabled').prop('disabled', '');
    $('#selectId').val(0);
    d.prop('disabled', 'disabled');
});

jsFiddle

Please keep in mind you can change the value of $('#selectId').val(0); to suite your own needs. For instance, if the 3rd option is your default and has a value of 'bob', then you could say $('#selectId').val('bob');

the answer i provided is just a simplest solution...@SpYk3HH modfied it if incase you default selected was disabled.... and yes @Felix Kling already answered this question in previous post here so have a look..anyways thanks guys..:)


Solution using Attribute via jQuery for Cross Compat

To further upon FelixKling's solution, here is the full jQuery version, using .attr which pulls from the original attributes as opposed to "changed properties" from .prop.

$(document).on('click', '#buttonID', function(e) {
        $('#selectID option').filter(function(i){ return this.hasAttribute('selected') }).prop('selected', 'selected')
});

jsFiddle Example


Combo Breaker !

To further solidify the solution, try a combo of the 2 above. This way, regardless of HTML layout, you're bound to reset to default. What I mean is, perhaps you don't have a select box with a set default, but rather option 1 is the default on load. Meanwhile, other selects do have a set default. The following will take care of both problems at the same time.

//    simply a jQuery 1.7+ way of delegating events to any Element match selector
$(document).on('click', 'button', function(e) {
    //    This both selects the first option of a select as well as looks for an option that might have had a default setting
    var opt = $('select').val(0).children('option').filter(function(i){ return this.hasAttribute('selected') });
    //    if opt.length is 0, this will do nothing and option 1 is already set, else this will set this default option to selected
    opt.prop('selected', 'selected');    
    // if you have an expected event tied to the select's "change" event, you might fire it here, like so:
    $('select').change();  
});

w/Out Comments, nice and short

$(document).on('click', 'button', function(e) {
    var opt = $('select').val(0).children('option').filter(function(i){ return this.hasAttribute('selected') });
    opt.prop('selected', 'selected');    
});

Example 1

Example 2 (with change event)

"to the original default value"

You don't say how you are setting the default, but if the default value is the first item you can say:

document.getElementById('selectIdHere').selectedIndex = 0;
// or with jQuery
$("#selectIdHere").prop("selectedIndex", 0);

Otherwise you can save the default item when the DOM is ready and set it back on the button click:

$(document).ready(function() {
    var $select = $("#selectIdHere");
    $select.data("default", $select.val());
    $("#buttonIdHere").click(function() {
         $select.val($select.data("default"));
    });
});

Note that you could just use a local variable in the ready handler instead of storing the value with .data() , but if you wanted to do this for more than one element it would probably be more manageable to use associate the default directly with the element using .data() .

I'd suggest you take a look at the DOM property defaultSelected .

EDIT: But this really depends on your HTML-markup. defaultSelected requires that one of the <option> 's has the selected property .

You just need to do this:

$("#yourresetbutton").on("click", function(){
   $("#yourDropDownId").val("default option value");
});

Here #resetbutton is the id of your reset button, #yourDropDownId is the id of your drop down and default option value will be the value of the default option that is selected by default.

Update if you want the disabled item to be selected, the above may not work, you may try this:

$("#yourresetbutton").on("click", function(){
   $("#yourDropDownId").find("option[val='yourDefaultValue']").attr("selected", "selected");
});

I suppose your HTML framework, or you, manually, are marking the default selected value from the DropDown like this, using the "selected" attribute.

<select id="myCombo" >
    <option >1</option>
    <option selected="selected">2</option>
    <option >3</option>
  </select>  

<button id="reset">Reset Select</button>

This attribute won't get overridden by the user interaction, only JS could mess with this flag, so, use this attribute to "remember" the default value.

$('#reset').click(function(){      
     var self = $('#myCombo');
     self.val(self.find('option[selected]').val());
});

In this way you dont have to add magic data- attributes, or any magic things that you (or the next developer) won't probably remember to set.

You can try it here:

http://jsbin.com/azupog/1/edit

当然,重置按钮可以完成您的工作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM