Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Multiple arguments to jQuery Function

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

like image 969
Kiran Avatar asked Oct 19 '25 02:10

Kiran


2 Answers

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
    });
  });
like image 92
CertainPerformance Avatar answered Oct 22 '25 05:10

CertainPerformance


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);
like image 29
Mrunmay Deswandikar Avatar answered Oct 22 '25 03:10

Mrunmay Deswandikar