Change background by clicking the checkbox

Asked

Viewed 303 times

1

I have a structure just like this

 <ul id="nomes">
    <li class="classli">
      <div class="Nome">Pedro</div>
      <div class="data">13/09/2017</div>
      <input class="check" type="checkbox">
   </li>
   <li class="classli">
      <div class="Nome">Lucas</div>
      <div class="data">13/09/2017</div>
      <input class="check" type="checkbox">
   </li>
</ul>

I am using this JS to generate ul/li

var obj = JSON.parse(req.responseText);

    document.getElementById("tabLista").innerHTML = "";

    var mydiv = document.getElementById("tabLista");
    var minhaul = document.createElement("ul"); 
    minhaul.setAttribute("id", "sul");  


    var novali = document.createElement("li");
    var novadivtipo = document.createElement("div");
    var novadivnome = document.createElement("div");
    var novadivtamanho = document.createElement("div");
    var novocheckbox = document.createElement("input");
    novali.setAttribute("class", "classli");

    novadivtipo.setAttribute("class", "tipo");
    novadivtipo.setAttribute("id", "Tipo" + R);
    novadivnome.setAttribute("class", "nomediv");                 
    novadivtamanho.setAttribute("class", "tamanhodiv");
    novocheckbox.setAttribute("class", "checkdelete");
    novocheckbox.setAttribute("type", "checkbox");

    img.setAttribute("class", "Icon");
    novadivtipo.appendChild(img);  

    novali.setAttribute("id", (obj.Lista[R].Nome));

    novali.appendChild(novadivtipo);
    novali.appendChild(novadivnome);
    novali.appendChild(novadivtamanho);
    novali.appendChild(novocheckbox);
    minhaul.appendChild(novali);
    mydiv.appendChild(minhaul);

My json I’m using to generate html

{
  "d": "api",
  "Lista": [
    {
      "Data": "12/12/2017",
      "Nome": "Lucas"
    }
  ],
  "arq": "3",
  "pasta": "5"
}

I want to click on the checkbox of each read and send the value of each name to an array and change the background of the read to another color, and when the checkbox is unchecked remove the same from the array, I found the solution only with jquery, but I would like a help to solve this problem only with pure js.

Thanks for the help :)

  • How are you generating this HTML? Maybe you can do this more reactively than reading HTML in the DOM.

  • Hello, I am recovering the data by a json and putting it through a createelement and setAttribute.

  • 1

    Okay, so there’s a more interesting way to do this :) You can put this code that inserts these ul/li?

  • I can yes, a moment

  • Both Pedro and Lucas come from the same JSON? or you have a json per element? I think I’m remembering another question from you... would you fetch the data one by one? then you have somewhere an arrays of jsons?

  • Pedro and Lucas come from the same JSON, the other question was related to this, the other I wanted to make a multi delete based on that list of names in each read, ai como eu clique na checkbox esse nome vai ser enviado para a função de multi delete, mais ou menos assim.

  • Ok, so JSON is an array of objects and when it is unchecked each checkbox you want to call a function and when it is checked call another function, and at the same time an array (JSON copy type) with the selected data (or this last array is not needed?)?

  • Json is an array of objects, when the person marks the checkbox of li I want the background to change color to give the effect of selected, and send the person’s name to an array (to use later in the function of the other question)and when unchecked the person’s name will exit that array.

Show 3 more comments

2 answers

3


Here is a suggestion. The code is generated from JSON, changes the color when selected and the current state of the selections is saved (and updated) in the variable escolhidas.

Suggestion:

// var obj = JSON.parse(req.responseText);
var json = [{
    nome: 'Pedro',
    data: '13/09/2017'
  },
  {
    nome: 'Lucas',
    data: '13/09/2017'
  },
]

var mydiv = document.getElementById("tabLista");
mydiv.innerHTML = "";
var ul = document.createElement("ul");
mydiv.appendChild(ul);

var escolhidas = [];
json.forEach(function(obj) {
  var li = document.createElement("li");
  ul.appendChild(li);
  Object.keys(obj).forEach(function(chave) {
    var div = document.createElement("div");
    div.classList.add(chave);
    div.textContent = obj[chave];
    li.appendChild(div);
  });
  var checkbox = document.createElement("input");
  checkbox.type = 'checkbox';
  checkbox.addEventListener('change', function() {
    this.closest('li').classList.toggle('selecionado', this.checked);
    if (this.checked) escolhidas.push(obj);
    else escolhidas = escolhidas.filter(function(el) {
      return el != obj;
    });
    console.log(escolhidas);
  });
  li.appendChild(checkbox);
});
.selecionado {
  background-color: #efe;
}
<div id="tabLista">
</div>

  • my name list is inside the other column inside the json, called List, I used obj. List[R]. Name to retrieve the names, how do I do this in this new example ?

  • @Planetwar in this case should suffice obj.Lista.forEach where I had json.forEach. If it doesn’t work show an example of this JSON that I adapt the answer.

  • 1

    Hello, I tried obj.list.foreach(Function(obj) { e obj.list.foreach(Function(obj) { e was not, a moment I’ll get the json

  • I edited the question and put the json, sorry anything, I’m new here :)

  • @There’s no need to apologize. Now you know that in the next time the more information you give at the beginning the better the answer :) Test like this: put obj = obj.List; on the line after json.forEach(function(obj) {.

  • 1

    Thank you, it worked perfectly :)

  • Ops, I was wrong, the system is printing [Object Object] in li, I would also like to know how I can set a different class for the name and date

  • @Planetwar my example is setting different classes in name and date. Take a look at HTML. You are using the JSON key.

Show 3 more comments

1

There are several ways to do this. Here is an alternative:

<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
 <ul id="nomes">
    <li id="classliopt1">
      <div class="Nome">Pedro</div>
      <div class="data">13/09/2017</div>
      <label for="opt1" id="lblopt1">
         <input class="check" id="opt1" type="checkbox" onclick="toggleCheckbox(this);"> teste
      </label>
   </li>
   <li id="classliopt2">
      <div class="Nome">Lucas</div>
      <div class="data">13/09/2017</div>
      <label for="opt2" id="lblopt2">
         <input class="check" id="opt2" type="checkbox" onclick="toggleCheckbox(this);"> teste
      </label>
   </li>
  </ul>
</body>
</html>

JS

function toggleCheckbox(handle) {
  var tmpElement = document.getElementById("classli" + handle.id)

  if (handle.checked){
    tmpElement.style.color = "#f00";
    tmpElement.style.backgroundColor = "#000";
  }
  else{
    tmpElement.style.color = "#000";
    tmpElement.style.backgroundColor = "transparent";
  }

}
  • how to do this using Event Systener ?

  • Inside the event "checkbox.addeventlistener('change', Function() {" you should implement the code I put in the example in the function "toggleCheckbox".

  • i am in doubt of how to use this to recoil the checkbox id, because it is generated dynamically

  • It is OK to generate it dynamically since you guarantee that the id will be unique for each element; just as I tried to show in the example by differentiating the LI’s with the suffix opt1, op2...

  • Thanks for the help :)

Browser other questions tagged

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