Reputation: 153
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!
Upvotes: 1
Views: 18808
Reputation: 59
Set the value in val()
and change()
function
jQuery(window).on('load', function () {
$('.mySelect').val(2).change();
});
Upvotes: 0
Reputation: 24648
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 );
});
Upvotes: 9
Reputation: 9060
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);
});
Upvotes: 1