Garmaine Staff asked 1 year ago

learning javascript by doing (beginner), here i have a table where is 'animals' and 'persons' want to know is there a way to reset table data back to 'Animal' after selecting data from select box ? i thought by calling the whole thing again inside onclick would do the trick but…

my code :

function myFunction() {
paivitys()
}

function paivitys(data, arvvoja) {
  console.log(data);
  //----
  if (data.hasOwnProperty("animal")) {
    document.getElementById("1name").innerHTML = data.animal;
  } else {
    document.getElementById("1name").innerHTML = data.person;
    document.getElementById("1name1").innerHTML = 'person';
  }
  //----		
  if (data.hasOwnProperty("animal2")) {
    document.getElementById("2name").innerHTML = data.animal2;
  } else {
    document.getElementById("2name").innerHTML = data.person2;
    document.getElementById("2name1").innerHTML = 'person';
  }

  //-----	
  document.getElementById("id").innerHTML = data.id;
}

function paivitaselekt(data, arvvoja) {
  for (var i = 0; i < data.length; i++) {
    var select = document.getElementById("Select");
    var option = document.createElement("option");
    arvvoja.forEach((value) => {
      option.textContent += data[i][value] + " ";
    });
    select.appendChild(option);
  }
}

data = {
  "animal": "tiger",
  "animal2": "lion",
  "id": "54321",
  "dole": {
    "Key": "fhd699f"
  }
}

paivitys(data);
let kokoarray;

data = [{
    "person": "kaka",
    "person2": "julle",
    "id": "9874",
  },
  {
    "person": "Ronaldo",
    "person2": "jussi",
    "id": "65555",
  }
]
kokoarray = data;
paivitaselekt(data, ["person", "id"]);

document.getElementById("Select").addEventListener("change", function(event) {
  const valittutunnsite = event.target.value.split(" ")[1];
  const valittutieto = kokoarray.filter((data) => data.id === valittutunnsite)[0];
  paivitys(valittutieto);
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous" />

<div class="container">
  <table class="table ">
    <thead>
      <tr>
        <th style="width: 25%;" id="1name1" class="table-primary">Animal</th>
        <th style="width: 25%;" id="2name1" class="table-primary">Animal</th>
        <th style="width: 25%;" class="table-primary">id</th>
      </tr>
    </thead>
    <tbody>
      <th id="1name"></th>
      <th id="2name"></th>
      <th id="id"></th>
    </tbody>
  </table>

  <select id="Select" name="name"></select>
  <button onclick="myFunction()">Reset</button>
</div>