In jQuery, I’m creating select boxes on the fly based on the number of items in a PHP array, and attempting to change the value of each select box option to the value of the array item.
First, here’s the HTML:
<div id="artistArea">
<div class="category_block">
<select name="artistSelect[]" class="cat_list">
<option value="">- none -</option>
</select>
</div>
</div>
Here’s the array conversion:
var arrayFromPHP = <?php echo json_encode($exhibArray) ?>; // There's our array from php->jquery
I then start by populating the options in the first select and then create the subsequent boxes within an ‘each’ loop in the ‘success’ callback:
$.ajax({
url: 'artistpop.php',
success: function(data){
$('.cat_list').append(data); //Sets options for first select box
$.each(arrayFromPHP, function (i, elem) { //loop through our array values
$("#artistArea > .category_block:last .cat_list").val(elem); //set the select box value
$('#artistArea > .category_block:last').after($('#artistArea > .category_block:last').clone()); //clone the previous select box
});
}
});
So… The problem is:
The initial box creation and population is working fine, as is the creation of the subsequent boxes. However, only the first select box is set with the appropriate value from the array; the others remain on the ‘none’ option.
Could this be something wrong in the each loop?
I hope this is clear enough to understand – I’m confused!
Have you tried setting a “selected” attribute on the actual option you want as your default, rather than setting the value of the select? In other words, something like…
$('#artistArea > .category_block:last .cat_list option[value=' + elem + ']').attr('selected','selected');