Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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($arry , ['UserId'=>'',"name":"name":"web1"]);

And then remove this line : $el.append('<option value="">Select your user</option>');

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading