Reputation: 8528
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
Upvotes: 4
Views: 1327
Reputation: 177786
Perhaps this is interesting?
note the escaping of the []
const fieldNames = ["product_id[]", "product_name[]", "manufacturer[]", "composition[]"];
const selector = fieldNames.map(item => `input[name='${item}\\\\[\\\\]']`).join(", ")
$rows.each((row) => {
$(selector).each(() => {
let idx = fieldNames.indexOf(this.name)
row.cells[idx].innerText = $(this).val(); // jquery object or collection?
})
})
Upvotes: 2
Reputation: 189
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);
Upvotes: 4
Reputation: 370689
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
});
});
Upvotes: 4
Reputation: 36564
Use ,
to separate multiple selectors
$("input[name='product_id[]'],input[name='product_name[]'],input[name='manufacturer[],input[name='composition[]']").each(function() {
});
Upvotes: 2