Home > Enterprise >  Loop through table form with Javascript and create objects from the values
Loop through table form with Javascript and create objects from the values

Time:11-06

Im trying to loop trough the table and create objects from each row. Each row contains 2 input fields and the values from those should be the properties of the object. As of now i am able to get the values, but only from the first row. Html:

<tbody>
    {{#each userArray}}
    <tr id="the_row">
      <th scope="row">1</th>
      <td><input type="checkbox" name="myValue" id="username" value="{{this.userName}}"/></td>
      <td>{{this.firstName}}</td>
      <td>{{this.grade}}</td>
      <td><input type="text" name="date" id=""/></td>
      <td>
    </tr>
    {{/each}}
  </tbody>

JS:

let users = [];

$("#btn").on("click", function () {
event.preventDefault();
$("#the_row :input").each(function () {

    console.log(this.value)
    //users.push({'name': this.value});  
  });
  
});

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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

getMyValues();

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

function getMyValues() {
const valuesObj = [...document.querySelectorAll('input, select')]
  .reduce( (acc, inp) => {
    if (inp.type === "radio") {
      acc[inp.name] = inp.value || `nothing selected yet`;
    }

    if (inp.type === "checkbox") {
      acc[inp.id] = inp.checked ? inp.value : `NOT:${inp.value}`;
    }

    if (/text|number/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" value="r1"> r1<br>
  <input type="radio" name="someRadio" value="r2"> r2<br>
  <input type="radio" name="someRadio" value="r3" checked> r3
</p>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related