Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice to store array of values in html attr?

What is the best practice to store an array of values in a html (from php) attribute and later access them from javascript/jQuery?

<div class="storage" someAttr=?? /></div>

Its basically a simple array like (code_1,code_2,code_3,...)
Im thinking of doing a simple someAttr="code_1;code_2;code_3" and then exploding it:

      var a = $(this).attr('someAttr');
      (a.split(";")).forEach(function (attr){
        console.log(attr);
      });
like image 491
Dainius Vaičiulis Avatar asked Aug 12 '15 13:08

Dainius Vaičiulis


1 Answers

You can json_encode your array on the PHP side, add it in as a data-attribute on the HTML side, and then parse it out on the JavaScript side.

<!DOCTYPE html>
<html>

  <head>
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
    <script>
      $(document).ready(function() {
        var jsArr = JSON.parse($('#phpArr').attr('data-attr'));
      });
    </script>
  </head>

  <body>
    <span id="phpArr" data-attr='<?php echo json_encode(arr); ?>'></span>
  </body>

</html>
like image 172
machinehead115 Avatar answered Oct 29 '22 23:10

machinehead115