I have a function which gets the data from various input ( multiple values ) and populate into a table.
Here is the jquery snippet :
var row =1
$("input[name='product_id[]']").each(function() {
$rows[row].cells[0].innerText = $(this).val();
row = row+1;
});
row=1;
$("input[name='product_name[]']").each(function() {
$rows[row].cells[1].innerText = $(this).val();
row = row+1;
});
row=1;
$("input[name='manufacturer[]']").each(function() {
$rows[row].cells[2].innerText = $(this).val();
row = row+1;
});
row=1;
$("input[name='composition[]']").each(function() {
$rows[row].cells[3].innerText = $(this).val();
row = row+1;
});
I was wondering if I can combine multiple iterators into a single iterator ?
Thanks Kiran
You can join the selectors by commas:
$("input[name='product_id[]'], input[name='product_name[]'], input[name='manufacturer[]'], input[name='composition[]']")
.each(function() {
// ...
});
To be more DRY, use an array:
const selectorStr = ['product_id', 'product_name', 'manufacturer', 'composition']
.map(str => `input[name='${str}[]']`)
.join(',');
$(selectorStr).each(function() {
// ...
});
If you need row to be 1 in all but the first iteration, then:
['product_id', 'product_name', 'manufacturer', 'composition']
.forEach((str, i) => {
if (i !== 0) {
row = 1;
}
$(`input[name='${str}[]']`).each(function(){
// etc
});
});
Create a common function, this will help your row logic, which gets value 1 before each iteration
function iteratorOperation(){
}
And then pass this to the iterators,
$("input[name='product_id[]']").each(iteratorOperation);
row=1;
$("input[name='product_name[]']").each(iteratorOperation);
row=1;
$("input[name='manufacturer[]']").each(iteratorOperation);
row=1;
$("input[name='composition[]']").each(iteratorOperation);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With