I'm trying to add the selected
attribute to the option
tag using jQuery (on a Wordpress site). The values that should be selected are stored in a PHP array. Why does the selected
attribute not get added to the <option>..
?
my-script.js
jQuery("#location option").each(function($){
var arr = [<?php echo '"'.implode('","', $php_array).'"' ?>];
// for testing also hardcoded array: doesn't work either
// var arr = ["1", "2"];
if(jQuery.inArray($(this).val(),arr) != -1){
$(this).attr('selected', 'selected');
};
});
The .js
script is properly enqueqed.
html-output
<select name="location[]" multiple="multiple" id="location" class="postform" style="display: none;">
<option value="-1">Select a location</option>
<option class="level-0" value="1">Location A</option>
<option class="level-0" value="2">Location B</option>
<option class="level-0" value="3">Location C</option>
</select>
The problem is because you cannot pass anything to the each
handler. Remove the $
from that and your code works fine:
var arr = ["1", "2"];
jQuery("#location option").each(function () {
if (jQuery.inArray($(this).val(), arr) != -1) {
$(this).prop('selected', true);
};
});