简体   繁体   中英

how do set select option 'selected' after load page?

i have code html

<select class="mySelect">
    <option value="1" >Date</option>
    <option value="2">Helpfulness</option>
</select>

Updated

So when the user selects 'Helpfulness' and reloads page then option Helpfulness should be 'selected'. and if 'Date' is choosen then reloaded page should set Date 'selected'.

thank for help!

Use .val() to set the value to 2 as follows:

$(function() {
    $('.mySelect').val( 2 );
});

 $(function() { $('.mySelect').val( 2 ); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select class="mySelect"> <option value="1">Date</option> <option value="2">Helpfulness</option> </select>

UPDATE

Per your updated question use localStorage or cookies to hold the selected value. When the page refreshes, check for the cookie or localStorage value and load it.

$(function() {
    $('.mySelect').on('change', function() {
        $.cookie('mySelect', this.value);
    });
    $('.mySelect').val( $.cookie('mySelect') || 1 );
});

DEMO

For most default value, it would be easy to set on html markup directly like :

<select class="mySelect">
  <option value="1" >Date</option>
  <option value="2" selected>Helpfulness</option>
</select>

Otherwise, use jQuery .prop code here :

$( function () {
   $('.mySelect option[value="2"]').prop('selected', true);
});

Set the value in val() and change() function

jQuery(window).on('load', function () {
    $('.mySelect').val(2).change();
});

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