Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display an element which is inside an array of an JSON object

Tags:

html

jquery

I can display an element of my JSON object but if it's inside an array then I got stuck.

Here is my code:

   $.ajax({
            method: "GET",
            url: api_url,
            // url: mock_url,
            contentType: "application/json",
            data: adminPrefData,
            success: function (res) {
                console.log(res);
                // callback(res);
                $('#module').text(res.module);  // i get this
                $('#networkId').text(res.networkId); // and this
                $('#adminPrefInfo.type').text(res.adminPrefInfo.type); // nothing happens on page
            },
            error: function () {
                $('#info').html('<p>An error has occured</p>');
            },
        });

Here is my HTML:

 <div class="content">
        <div class="nav-link-content home">
            <h1 class="text-center" id="module"></h1>
            <div class="text-center" id="networkId"></div>
            <div class="text-center" id="adminPrefInfo.type"></div>
        </div>
</div>

Here is my JSON I get:

{"module":"dnd","networkId":1,"adminPrefInfo":[{"id":1,"key":"teszt","value":"teszt","defValue":"teszt1","type":"checkbox","isActive":true}]}

like image 784
Kerk Avatar asked Jan 31 '26 18:01

Kerk


1 Answers

The first issue is because you have a period in the id attribute of the HTML element. You need escape it in the jQuery selector with \\. The second issue is that adminPrefInfo is an array. As such you need to access it by index, then get the type property. Try this:

$('#adminInfoList\\.type').text(res.adminPrefInfo[0].type);
like image 142
Rory McCrossan Avatar answered Feb 03 '26 08:02

Rory McCrossan



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!