I am working with php and i want to change value of dropdown using jquery, i want to pass php array into jquery variable(make dynamic dropdown value) Right now i am getting array($data) in following format
Array
(
[0] => stdClass Object
(
[UserId] => 8
[name] => web1
)
[1] => stdClass Object
(
[UserId] => 9
[name] => web2
)
)
And here is my script which is showing static "dropdown" values,but i want to pass php array (name) values to dropdown so i can make dynamic dropdown
<script>
var newOptions = {
"Select your user":"",
"Option 1":"option-1",
"Option 2":"option-2"
};
var $el = $('#acf-field_628e17fc947e4');
$el.html(' ');
$.each(newOptions, function(key, value) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
</script>
CodePudding user response:
var newOptions = <?php echo json_encode($array); ?>;
and then change your append line to this and you are good to go
$el.append('<option value="' value.UserId '">' value.name '</option>');
Working snippet:
var newOptions = [{"UserId":8,"name":"web1"},{"UserId":9,"name":"web2"}];
var $el = $('#acf-field_628e17fc947e4');
$el.html(' ');
$el.append('<option value="">Select your user</option>');
$.each(newOptions, function(key, value) {
$el.append('<option value="' value.UserId '">' value.name '</option>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="acf-field_628e17fc947e4"></select>
Note: to add select option, add it in array like this:
array_unshift($array , ['UserId'=>'',"name":"name":"web1"]);
And then remove this line : $el.append('<option value="">Select your user</option>');
CodePudding user response:
You have an array to pass from PHP to JS so you can use json_encode like: (The example below is dynamic)
<?php
$phpArray = array(
0 => "Mon",
1 => "Tue",
2 => "Wed",
3 => "Thu",
4 => "Fri",
5 => "Sat",
6 => "Sun",
)
?>
<script type="text/javascript">
var jArray = <?php echo json_encode($phpArray); ?>;
for(var i=0; i<jArray.length; i ){
alert(jArray[i]);
}
</script>