Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
114
rated 0 times [  115] [ 1]  / answers: 1 / hits: 91115  / 12 Years ago, mon, september 24, 2012, 12:00:00

Below is code for select option and generate using php from database and i try to add selected=selected to value=4 using jQuery or any javascript:



<select id=countryselect name=country>
<option value=1>Afghanistan</option>
<option value=2>Albania</option>
<option value=3>Algeria</option>
<option value=4>Malaysia</option>
<option value=5>Maldives</option>
</select>


i try to refer this post but still can't .. below is my current script :



<script>
localStorage.setItem(Select1, Malaysia);
$('#countryselect').find('option').each(function(i,e){
if($(e).val() == localStorage.getItem(Select1)){
$('#countryselect').prop('selectedIndex',i);
}
});
</script>


thanks.


More From » jquery

 Answers
16

localStorage.getItem(Select1) will return Malaysia and $(e).val() will return 1,2...5 in each loop. So your condition will never be true. Instead use



<script>
localStorage.setItem(Select1, 4);
$('#countryselect').find('option').each(function(i,e){
if($(e).val() == localStorage.getItem(Select1)){
$('#countryselect').prop('selectedIndex',i);
}
});
</script>

[#82943] Friday, September 21, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stacie

Total Points: 476
Total Questions: 92
Total Answers: 102

Location: Bosnia and Herzegovina
Member since Tue, Mar 29, 2022
2 Years ago
stacie questions
Fri, Jun 26, 20, 00:00, 4 Years ago
Thu, Jan 23, 20, 00:00, 4 Years ago
Fri, Aug 30, 19, 00:00, 5 Years ago
Fri, Aug 2, 19, 00:00, 5 Years ago
;