I am populating a dropdown on page load using some business logic and one of the values MAY (or may not) be selected, depending on the if conditions.
I am not able to:
- Find which value is selected after load, if any
- trigger the 'onChange' function for that dropdown using that selected value, if any value was selected
A sample code I am trying is here: http://jsfiddle.net/v7QWd/1203/
<div id="outerDiv">
<select id="myDropdown" class="check">
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
<option value="four">four</option>
</select>
</div>
$(document).ready(function () {
//call on load
someFunction();
$(document).on('change', '#myDropdown', function() {
localStorage.setItem('selected_val', $(this).val());
alert($(this).val());
});
function someFunction(){
var mycondition = "true";
//run busines slogic
var htmlVar = "";
if(mycondition == 'true'){
htmlVar = '<select id="myDropdown" class="check">'+
'<option value="one">one</option>'+
'<option value="two">two</option>'+
'<option selected = "selected" value="three">three</option>'+
'<option value="four">four</option>'+
'</select>';
}
$("#outerDiv").empty();
$("#outerDiv").append(htmlVar);
}
});
The function should fire itself for the value 'three' (value can change based on run time conditions). So basically, on page load, 'three' should be alerted in this example.