Estoy tratando de recorrer un formulario de tabla y crear objetos de cada fila. Cada fila contiene 2-3 campos de entrada y los valores de esos deben ser las propiedades del objeto. El objeto solo debe almacenarse si la casilla de verificación correspondiente a esa fila está marcada.
EDITAR: se me ocurrió una solución. Soy nuevo en Javascript, así que dé su opinión si esto se puede mejorar de alguna manera.
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); });Lo siento por la intención es el archivo JS.
Si solo está enviando un formulario, puede usar FormData para recopilar los nombres de los campos y sus valores, y luego convertirlos en un objeto.
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>Un ejemplo (no tan mínimo pero) reproducible para crear un objeto a partir de los valores actuales de los elementos de entrada/selección en el documento (nota: no se usa ningún formulario aquí).
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>