Reputation: 1930
I'm trying to select the option based on the php variable value. So I need option value=1
is selected in the first <select>
and option value=6
selected in second . Since I have a bunch of other <select>
in the form, eventually, I will have an php array of some values, and I need each of the value match up with the option value under corresponding index in the a group of <select>
that sharing the same class='si_1'
, and assign selected
to that option.
Thanks
php part
<?php
$select_1 = "1";
$select_2 = "6";
?>
JQuery part
$(document).ready(function(){
var sel_class = $(".si_1");
var array = {"<?php echo $select_1?>","<?php echo $select_2?>"};
JQuery.each(array, function(index, value) {
var current = sel_class.get(index);
$(current + " option[value=" + value + "]").attr('selected', 'selected');
});
});
I don't know if $(current + " option[value=" + value + "]")
is the correct syntax to target the <select>
at index in $(".si_1")
that has option
where the option attribute value
has value that's at index in array
HTML part
<select class="si_1">
<option value="1">Test 1</option>
<option value="3">Test 3</option>
<option value="5">Test 5</option>
<option value="7">Test 7</option>
</select>
<select class="si_1">
<option value="2">Test 2</option>
<option value="4">Test 4</option>
<option value="6">Test 6</option>
<option value="8">Test 8</option>
</select>
Upvotes: 0
Views: 286
Reputation: 1893
You can do this in the JavaScript:
selectedVal1 = "<?= $select_1; ?>";
selectedVal2 = "<?= $select_2; ?>";
When the client looks at it, it will look like this:
selectedVal1 = "1";
selectedVal2 = "6";
Then it's just using jQuery to set the selected
attribute to selected
(Just do .attr('selected', 'selected'))
Upvotes: 1