Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace jquery variable values with php array values

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>
like image 864
Amy Avatar asked Dec 06 '25 10:12

Amy


1 Answers

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>');

like image 80
Anant Kumar Singh Avatar answered Dec 07 '25 23:12

Anant Kumar Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!