vendredi 12 août 2022

JavaScript: how to undo a checkbox change event? [duplicate]

I have a list of articles in a HTML table and each row has a cell with a checkbox at the end, so that an article can be (un)selected. When the user clicks a checkbox, its onchange event performs a test in the database, that can either return true or false. When false is returned, i want to undo the click action, so that the old checkbox value is restored:

chb.checked = !chb.checked

Unfortunately, this does not work. The chb.checked value changes, but not the checkbox itself. I think that this is due to the fact that the assignment is taking place inside the onchange event.

The checkbox is created in this way:

chb = document.createElement("input");
chb.type = "checkbox";
chb.onchange = () => toggle_movi_status(chb,imdb)

The onchange function looks as follows:

async function toggle_movi_status(chb,imdb) {
  var url;

  var formData = new FormData();
  formData.append("user", JSON.stringify(g_user));
  url = "util.php?func=toggle_movi_status&imdb=" + imdb;
  await fetch(url, {
    method: 'POST',
    body: formData})
    .then((resp) => resp.json())
    .then(function(data) {
      if (data.status != "ok")
        chb.checked = !chb.checked; /* = undo */
    })
    .catch(function(error) {
    });
}

Could anybody please clarify this for me and/or offer me a solution that works? Plain vanilla JS please.




Aucun commentaire:

Enregistrer un commentaire