Is it a good practice to store a JSON object in a data-attribute?

3
<button type="button" class="btn btn-info btn-lg questao" data-json="" data-toggle="modal" data-target="#myModal">Open Modal</button><BR/>
<button type="button" class="btn btn-info btn-lg questao" data-json="" data-toggle="modal" data-target="#myModal">Open Modal</button><BR/>
<button type="button" class="btn btn-info btn-lg questao" data-json="" data-toggle="modal" data-target="#myModal">Open Modal</button>



$(document.body).on("click",".questao",function(){
  var thisPosicao = $(".questao").index(this);
  var thisElement = $("#myModal").find(".modal-body").find("input");
  var array = [];
  thisElement.data("posicao",thisPosicao);
  //addTo.val(addTo.data("posicao");

  array.push({
    "posicao": thisElement.data("posicao"),
    "teste": "questao"+thisPosicao
  });

  $(".questao").eq(thisPosicao).data("json", JSON.stringify(array));
  var getJson = $(".questao").eq(thisPosicao).data("json");


  alert(JSON.stringify(getJson));
});

In the future there will be a loop to go through all these buttons to get the data-json and send via ajax. Remembering that this is just a simple example, in my project there will be millions of options for the user to select as setting before sending via ajax.

Is it a good practice to store a JSON in a data-attribute ? I have a project that will have to loop and grab all the information stored in every input of different types (get the checked value of a checkbox , the value entered in a input text , etc).

In this project there will also be a modal to select more configuration options, my idea was to store this data inside a data-atribute to be read and stored in another json file (it will be sent to the server with all configurations which the user did).

An example I made: link

    
asked by anonymous 25.03.2016 / 01:34

2 answers

2

Tools exist to be used. It depends on the logic you have, whether it is better to separate the data you want in several data- or have only one data-json with a JSON in it. Both are correct, both are good practice.

    
25.03.2016 / 10:16
2

Generally speaking, no problem. Have you considered using AngularJS? It has a feature that maps an element directly to a template, and it automatically syncs to you.

    
25.03.2016 / 03:00