Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

250
Visualizações
How do i get total value of scores in the table?

HTML:

<table>
  <tr>
    <th>Student Name</th>
    <th>Student Score</th>
  </tr>
  <tr>
    <td>
      <select name="dropdown" id="dropdown" onchange="showScore()">
        <option> - </option>
        <option id="StudentA"> Student A </option>
        <option id="StudentB"> Student B </option>
      </select>
    </td>
    <td></td>
  </tr>
  <tr>
    <td>
      <select name="dropdown" id="dropdown" onchange="showScore()">
        <option> - </option>
        <option id="StudentA"> Student A </option>
        <option id="StudentB"> Student B </option>
      </select>
    </td>
    <td></td>
  </tr>
</table>

JS:

const data = {
  "students": [{
    "studentName": "studentA",
    "studentScore": "60"
  }, {
    "studentName": "studentB",
    "studentScore": "50"
  }, ]
}

function showScore() {
  const dropdowns = document.querySelectorAll('#dropdown')
  dropdowns.forEach(dropdown => {
    const selectedVal = dropdown.options[dropdown.selectedIndex].id
    const formattedVal = selectedVal.charAt(0).toLowerCase() + selectedVal.slice(1)
    const score = data.students.map(item => {
      if (item.studentName == formattedVal) {
        dropdown.parentElement.parentElement.children[1].innerText = item.studentScore;
      }
    })
  })
}

How do i automatically get the value of total scores of each student? and also how do move the const data into php and make it hidden and call in the function using ajax? thank you for helping me.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Like mentioned in the comments above, it would be recommended to ensure each ID is unique and maybe use value instead to ID in the selects.

You can make use of the querySelectorAll attribute to map over the information and get the total scores using a [data-score] attribute on the table column.

See my changes to allow for this

const data = {
  "students": [{
    "studentName": "studentA",
    "studentScore": "60"
  }, {
    "studentName": "studentB",
    "studentScore": "50"
  }, ]
}

function showScore() {
  const dropdowns = document.querySelectorAll('#dropdown')
  dropdowns.forEach(dropdown => {
    const selectedVal = dropdown.options[dropdown.selectedIndex].id
    const formattedVal = selectedVal.charAt(0).toLowerCase() + selectedVal.slice(1)
    const score = data.students.map(item => {
      if (item.studentName == formattedVal) {
        dropdown.parentElement.parentElement.children[1].innerText = item.studentScore;
      }
    })
  })
  
  // Sum total score
  let scores = document.querySelectorAll("[data-score]")
  let scoresInt = [...scores].map(item => parseInt(item.textContent) || 0)
  let sum = scoresInt.reduce((a, b) => a + b, 0)
  document.querySelector("#totalScore").innerHTML = sum
}
<table>
  <tr>
    <th>Student Name</th>
    <th>Student Score</th>
  </tr>
  <tr>
    <td>
      <select name="dropdown" id="dropdown" onchange="showScore()">
        <option> - </option>
        <option id="StudentA"> Student A </option>
        <option id="StudentB"> Student B </option>
      </select>
    </td>
    <td data-score></td>
  </tr>
  <tr>
    <td>
      <select name="dropdown" id="dropdown" onchange="showScore()">
        <option> - </option>
        <option id="StudentA"> Student A </option>
        <option id="StudentB"> Student B </option>
      </select>
    </td>
    <td data-score></td>
  </tr>
</table>
<div>
Total Score
</div>
<div id="totalScore">0</div>

I created a few variables to get the instances of all scores, then use the ES6 reduce method to accumulate these and set that value into the div for total scores.

about 4 years ago · Juan Pablo Isaza Relatório

0

The Array.prototype.reduce() method is best suited for operations like this (sum total).

const sumTotal = arr =>
  arr.reduce((sum, { price, quantity }) => sum + price * quantity, 0)

const data = [
  { id: 1, price: 30, quantity: 2 },
  { id: 2, price: 20, quantity: 4 },
  { id: 3, price: 10, quantity: 2 },
]

const total = sumTotal(data);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda