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

Asked

Viewed 237 times

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 pick up 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 configuration before sending via ajax.

It is good practice to store a JSON in a data-attribute? I have a project that will have to loop and get all the information stored in each input of different types (take the checkvalue of a checkbox, the value typed in a input text, etc.).

In this project there will also be a modal to select more settings options, my idea was to store this data within a data-atribute to then be read and stored in another json file (this will be sent to the server with all the settings the user has made).

an example I made: https://jsfiddle.net/cr9nucw3/

2 answers

2

Generally speaking, no problem. Have you considered using Angularjs? It has a feature that maps an element to a model directly, and automatically synchronizes to you.

2


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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.