I have a drop down list which is dynamically generated using ajax on page load.
On the other hand I have a php variable which contains the value to be selected by default.
However, when Iam trying to do this it isn’t selecting the value. Following is code:
HTML & PHP
<h1>Venue: Edit</h1>
<a href="/venue"><< Back to Venue List</a>
<br />
<form method="post" id="venueEdit" action="<?php echo URL;?>venue/editSave/<?php echo $this->venue['id']; ?>">
<fieldset>
<p>
<label for="cvenue" class="main">Venue</label>
<input id="cvenue" class="required" type="text" name="venue" value="<?php echo $this->venue['name']; ?>" />
</p>
<p>
<label for="ccity" class="main">City</label>
<input id="ccity" class="required" type="text" name="city" value="<?php echo $this->venue['city']; ?>" />
</p>
<p>
<label for="ccountry" class="main">Country</label>
<select id="ccountry" class="required" name="country">
<option value="">-- Select Country --</option>
</select>
</p>
<p>
<label class="main"> </label><input type="submit" value="Save" />
</p>
</fieldset>
</form>
JS:
function populateCountryDropDown(url){
$.get(url, function(o) {
for(var i = 0; i < o.length; i++){
$('select[name="country"]').append('<option value="' + o[i].id + '">' + o[i].name + "</option>");
}
}, 'json');
}
$(document).ready(function(){
populateCountryDropDown('<?php echo URL; ?>' + 'country/xhrGetCountryList');
$('select[name="country"]').val('<?php echo $this->venue['countryid']; ?>');
$("#venueEdit").validate();
});
I tried to alert the php value and it’s ok but if I alert the select option value it’s always null as at that point it’s still populating the drop down list. I don’t know how to solve this. Would appreciate your guys help? Thanks.
You need to move your code to set the value into the callback, to trigger the value being set after the AJAX call fired off by
$.get()returns.