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

138
Visualizações
Loop through table form with Javascript and create objects from the values

Im trying to loop through a table form and create objects from each row. Each row contains 2-3 input fields and the values from those should be the properties of the object. The object should only be stored if the checkbox corresponding to the that row is checked.

EDIT: I came up with a solution. Im new to Javascript so please give input if this can be improved somehow.

Html:

 <table class="table">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">Markera</th>
      <th scope="col">Användarnamn</th>
      <th scope="col">Namn</th>
      <th scope="col">Omdöme i Canvas</th>
      <th scope="col">Examinationsdatum</th>
    </tr>
  </thead>
  <tbody>
    {{#each userArray}}
    <tr class="the_row">
      <th scope="row">1</th>
      <td><input type="checkbox" name="checkbox"/></td>
      <td><input type="text" name="username" value="
      {{this.userName}}"  readonly /></td>
      <td>{{this.firstName}}</td>
      <td>{{this.grade}}</td>
      <td><input type="text" name="date"/></td>
    </tr>
    {{/each}}
  </tbody>
</table>

JS:

let users = [];

$("#btn").on("click", function () {
event.preventDefault();

$(".table tr").each(function () {

let user = {};

$(this).find("input").each(function () {


  if($(this).attr("name") =='checkbox' && $(this).prop("checked")
  == true){
    user[$(this).attr("name")] = $(this).prop("checked");

  }
  else{
    user[$(this).attr("name")] = $(this).val();
  }

  });

  
  if(user.checkbox===true){
    users.push(user);
  }
});

console.log(users);
});

Sorry about the intending is the JS file.

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

0

If you are just submitting a form, you could use FormData to gather the field names and their values, then turn that into an object.

const form = document.querySelector('.myForm')

form.addEventListener('submit', (e) => {
  e.preventDefault()
  const object = {};
  const myFormData = new FormData(form)
  myFormData.forEach((value, key) => object[key] = value);
  console.log(object)
})
<form class="myForm">
  <table>
    <tbody>
      <tr>
        <th>1</th>
        <td><label>checkbox: <input type="checkbox" name="row1checkbox"/></label></td>
        <td><label>text: <input type="text" name="row1text" /></label></td>
      </tr>
      <tr>
        <th>2</th>
        <td><label>checkbox: <input type="checkbox" name="row2checkbox"/></label></td>
        <td><label>text: <input type="text" name="row2text" /></label></td>
      </tr>
      <tr>
        <th>3</th>
        <td><label>checkbox: <input type="checkbox" name="row3checkbox"/></label></td>
        <td><label>text: <input type="text" name="row3text" /></label></td>
      </tr>
    </tbody>
  </table>
  <button type="submit">submit</button>
</form>

about 4 years ago · Juan Pablo Isaza Relatório

0

A (not that minimal but) reproducable example to create an object from the current values of input/select elements in the document (note: no form used here).

See also

getMyValues();

const handle = evt => {
  if (/input|select/i.test(evt.target.nodeName)) {
    return getMyValues();
  };
}
document.addEventListener(`click`, handle);
document.addEventListener(`keyup`, handle);

function getMyValues() {
  console.clear();
  const valuesObj = [...document.querySelectorAll('input, select')]
    .reduce( (acc, inp) => {
      if (/radio|checkbox/i.test(inp.type)) {
        acc[inp.id] = inp.checked ? `on:${inp.value}` : `off:${inp.value}`;
      }
      // note: you may want to include types like range/search/url etc. 
      // See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input
      if (/text|number|textarea|date/i.test(inp.type)) {
        acc[inp.id] = inp.value || `empty`;
      }
      
      if (inp.constructor === HTMLSelectElement) {
        acc[inp.id] = inp.value;
      }

      return acc;
    }, {});
        
  document.querySelector(`pre`).textContent = `Your values:\n${
    JSON.stringify(valuesObj, null, 2)}`;
  }
body {
  font: 12px/15px normal verdana, arial;
  margin: 2rem;
}

pre {
  position: absolute;
  width: 45vw;
  left: 50vw;
  top: 1rem;
  padding: 5px;
  border: 1px solid #AAA;
}

input,
select {
  margin-bottom: 6px;
}
<pre></pre>
<p>
  <input type="number" value="4" id="someNumber"> some number<br>
  <input type="checkbox" value="cb4" id="someCheckbox"> some checkbox<br>
  <input type="text" placeholder="some text" id="someText" value="tx txt text"> some text<br>
  <input type="text" placeholder="some text" id="someText2"> some text<br>
  <select id="selectSome">
    <option value="v1">v1</option>
    <option value="v2" selected>v2</option>
    <option value="v3">v3</option>
  </select><br>
  <select id="selectSome2">
    <option value="nothing selected yet">select one</option>
    <option value="vv1">vv1</option>
    <option value="vv2">vv2</option>
    <option value="vv3">vv3</option>
  </select><br>
  <input type="radio" name="someRadio" id="radio1" value="r1">r1<br>
  <input type="radio" name="someRadio" id="radio2" value="r2">r2<br>
  <input type="radio" name="someRadio" id="radio3" value="r3">r3
</p>

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