Retrieve checkbox serializeArray value

Asked

Viewed 56 times

0

I have a form with several Hecklist. Clicking the array is saved in the textarea.

Question

Assuming the data is already saved in the BD, when the person is editing, how to load the checkbox that has already been checked?

$(document).on("click", "input[name='ar']", function() {
  let ar = $(".panel input[name='ar']").serializeArray();
  console.log(JSON.stringify(ar))
  document.getElementById("arrayAres").innerHTML = JSON.stringify(ar);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>



<button class="accordion"># AR 1</button>
<div class="panel">
  <p>
    <input type="checkbox" name="ar" /> BVBV
    <input type="checkbox" name="ar" /> GFGF
    <input type="checkbox" name="ar" /> AFAFA
  </p>
</div>

<button class="accordion"># AR 2</button>
<div class="panel">
  <p>
    <input type="checkbox" name="ar" />GFHG
    <input type="checkbox" name="ar" />JHJHK
    <input type="checkbox" name="ar" />KILIL
  </p>
</div>

<button class="accordion"># AR 3</button>
<div class="panel">
  <p>
    <input type="checkbox" name="ar" />TYT
    <input type="checkbox" name="ar" />FAFG
    <input type="checkbox" name="ar" />GJK
  </p>
</div>

<textarea name="" id="arrayAres" rows="5" placeholder="arrayAres"></textarea>

1 answer

1

From what I understand it’s this textarea that you will store in BD right?

If so, just add the Id field to each of your checkboxes (you can do it without Id, but it is recommended to treat the elements in the DOM with id) and save the Ids also in your textarea.

Then, simply iterate between the array elements you saved in the BD and set checked to true in all of the following ways:

const textarea = [{"name":"ar","value":"on", "id": "check1"},{"name":"ar","value":"on", "id": "check2"},{"name":"ar","value":"on", , "id": "check3"}]

textarea.forEach(checkbox => {
    document.getElementById(checkbox.id).checked = true
})

Browser other questions tagged

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