Reputation: 1489
Morning,
I have a select box which looks like this:
<select id="companyselect" name="companyselect">
<option value="-1">Please choose company</option>
<option value="CO1">CO1</option>
<option value="CO2">CO2</option>
<option value="CO3">CO3</option>
<option value="CO4">CO4</option>
</select>
All options, apart from the first, are generated using jQuery (from localStorage) and appear as they should.
I have a jquery function which is triggered on the 'change' event:
$(document).on('change', '#companyselect', function(e){
thecomp = $('#companyselect').val();
alert(thecomp);
});
This all works fine.
However, when I reload the page, all options are generated as expected but the 'change' event is not working as required. No matter what option is selected, $('#companyselect').val();
is always returned as the first option.
I have checked the DOM to see if there is another element with the same id, but no. I have tried returning the text of the option, and it returns the text of the first option.
All suggestions are most welcome.
Upvotes: 0
Views: 1606
Reputation: 1489
The solution, which somebody put on here but then deleted, is to replace
thecomp = $('#companyselect').val();
with
thecomp = $(this).val();
Thanks to whomever posted the answer originally
Upvotes: 0
Reputation: 6907
Here is how you use localstorage to get the selected value even after use refreshes the page using jquery using localstorage,
$(document).on('change', '#companyselect', function(e){
var thecomp = $('#companyselect').val();
localStorage.thecomp=thecomp;
alert(thecomp);
});
if(localStorage.getItem('thecomp')){
alert(localStorage.thecomp);
$("#companyselect").val(localStorage.thecomp);
}
Upvotes: 2