deepak.mr888
deepak.mr888

Reputation: 349

Set an option as selected from select dropdown using jquery

I have a select dropdown list having n number of options, i want on page load, option which i selected earlier should get selected in dropdown using jquery :

Here is my html code :

<select id="myList">
<option value="1">first</option>
<option value="2">second</option>
<option value="3">third</option>
</select>

<input type="hidden" value="1" id="hiddenoptionid" />

Here is my jquery code :

$(document).ready(function() {
var projectId=document.getElementById("hiddenoptionid").value;
$("#myList option[value="+projectId+"]").attr("selected", "selected");
});

$("#projectlist").on('change', function() {
            var id = $(this).val();
document.getElementById("hiddenoptionid").value=id;
location.reload(); 
});

Thanks.

Upvotes: 0

Views: 177

Answers (1)

Anoop Joshi P
Anoop Joshi P

Reputation: 25527

You can use like,

$(document).ready(function(){
   $("#projectlist").val($("#hiddenoptionid").val());
});

Note that, if you reload the page, $("#hiddenoptionid").val() will get reset to 1 again. If you want to retain that value, use cookies for that

Upvotes: 1

Related Questions