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 decode symbols " and others symbols to manipulate this data in JS?

In PHP, I put the $data_attributes array into the data-additional-color-data attribute of one HTML element:

$data_attributes = [
      312 => [
        'name' => 'Black',
        'hex' => '#000000',
        'src' => 'http://sitename/files/pms_colors/Black.png'
      ],
      313 => [
        'name' => 'Metallic',
        'hex' => '#D3D4DE',
        'src' => 'http://sitename/files/pms_colors/Metallic.png'
      ]
    ];
$entity_form['field_pms_colors']['#attributes']['data-additional-color-data'] = Json::encode($data_attributes);

And I see in the browser’s devtools that in the markup the element looks like this:

<div class="field--name-field-pms-colors" data-additional-color-data="{&quot;312&quot;:{&quot;name&quot;:&quot;Black&quot;,&quot;hex&quot;:&quot;#000000&quot;,&quot;src&quot;:&quot;http:\/\/sitename\/sites\/default\/files\/pms_colors\/Black.png&quot;},&quot;313&quot;:{&quot;name&quot;:&quot;Metallic Silver&quot;,&quot;hex&quot;:&quot;#D3D4DE&quot;,&quot;src&quot;:&quot;http:\/\/sitename\/sites\/default\/files\/pms_colors\/Metallic%20Silver.png&quot;}}"></div>

This is one element and its properties must be with it:

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

      312 => [
        'name' => 'Black',
        'hex' => '#000000',
        'src' => 'http://sitename/files/pms_colors/Black.png'
      ],

>Solution :

There is no specific decoding to be done, as JavaScript will decode this when accessing the data attribute like this:

// Get the HTML element of interest:
let element = document.querySelector("div.field--name-field-pms-colors");
// Read the data- attribute of interest:
let content = element.dataset.additionalColorData;
// Output it: no decoding of HTML entities needed -- there is no literal &quot;
console.log(content);
// Parse the JSON into an object
let obj = JSON.parse(content);
// Use the object...
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