How to assign array items to a list of inputs

Hi all,
I have a small issue I tried to figure it out but I failed , hope to find a solution here.
When I ran the next code I can get all the inputs values with class name(“unit-purchase-price”) it comes in the right sequence

let inps = $('table .unit-purchase-price');
inps.each(index => {
   $(inps[index]).val();
   alert($(inps[index]).val());
})

But when I try to assign values to the same inputs, I failed (once the inputs become empty and once become the last value of my ARRAY)
I know I miss something but I failed to find it …
The next lines illustrate my tries

let unitPrice = [
    "8.00000",
    "100.00000",
    "395.00000",
    "600.00000",
    "415.00000"
]
let inps = $('table .unit-purchase-price');
unitPrice.forEach(element => {
   // alert(element)
   inps.each(function (i){
        $(this[i]).val(element)
    })
})

I thought the last code snippet would help to assign the values of unitPrice array to the list of inps inputs , But unfortunately it failed to achieve the mission…
Also I searched for a solution on the web and on the JQuery Docs .
Any advises to solve this issue

My first suggestion would be to add console.log($(this[i])) before the line you are using it in to verify that it’s the value you actually want.

1 Like

I would suggest you look at the each method in the docs.

https://api.jquery.com/each/#each-function


Also, you definitely do not need jQuery for this. And if you are sure the two arrays are of the same length you do not need two loops as one will provide the index for the other, but you can always set a default value just to be sure.

let unitPrice = ["8.00000", "100.00000", "395.00000", "600.00000", "415.00000"];
const inputs = document.querySelectorAll("input");

inputs.forEach((input, index) => {
  input.value = unitPrice[index] ?? 0;
});
1 Like

Thanks @bbsmooth , I appreciate your reply so much.
Really I used console.log() in every step in my project.
And you are right
the next line is wrong

It must be $(inps[i]).val(element)

Many thanks @lasjorg ,
Really your idea about unitPrice[index] do the mission and fix my issue but without your code , because it gives me input.forEach is not a function

the next code do the job as expected

let inps = $('table .unit-purchase-price');
inps.each(function(i) {                    
   let myInp = $(inps[i]);
   console.log(
      'VALUE:', $(inps[i]).val(), 
      'ASSIGN-INPUT.VALUE::', myInp.val(unitPrice[i])
     );
    // Both lines give the same result
   // $(inps[i]).val(unitPrice[i]);
   myInp.val(unitPrice[i]);
});

The problem was in the twice loop as you said

Thanks again

The code I posted does not use input.forEach but inputs.forEach it is plural inputs (i.e. all the input elements returned from querySelectorAll).


As for your code, this inside the each method is each of the elements. So you can do $(this).val(unitPrice[index])

Or you can use the second parameter for the each callback which is also the element (that lets you use an arrow function for the callback as well).

const unitPrice = [
  "8.00000",
  "100.00000",
  "395.00000",
  "600.00000",
  "415.00000"
];

// using "this", callback must be a normal function
$(".unit-purchase-price").each(function (index) {
  $(this).val(unitPrice[index]);
});

// or using the second parameter
$(".unit-purchase-price").each(function (index, element) {
  $(element).val(unitPrice[index]);
});

// Same thing as above but an arrow function for the callback
$(".unit-purchase-price").each((index, element) =>
  $(element).val(unitPrice[index])
);

1 Like

@lasjorg You are right it works but with some modifications
when I used it at the first time I used getElementsByClassName

const inputs = document.getElementsByClassName("unit-purchase-price");

So forEach throw an Error inputs.forEach is not a function
Now I tried it again like this

const inputs = document.querySelectorAll(".unit-purchase-price");

                    inputs.forEach((input, index) => {
                        input.value = unitPrice[index] ?? 0;
                        console.log('INPUT***', input, index)
                    });

It worked as expected Thanks…

But I used the code of my last post as

let inpsPurchase = $('table .unit-purchase-price');
let inpsValue = $('table .unit-price-value');
let inpsPercentage = $('table .unit-price-percentage');
let inpsSalePrice = $('table .unit-sale-price');

inpsPurchase.each((i) => {
      let myInp = $(inpsPurchase[i]);
      let mySalePrice = $(inpsSalePrice[i]);
      let myValue = $(inpsValue[i]);
      let myPercentage = $(inpsPercentage[i]);
      
      myInp.val(unitPrice[i]); // Here we assign the new value to the inputs
      mySalePrice.val(parseFloat(myInp.val()) + parseFloat(myValue.val()));
      myPercentage.val(parseFloat( (myValue.val()) / parseFloat(myInp.val()) ) * 100)
  console.log(
     'inpsPurchaseVALUE:::', $(inpsPurchase[i]).val(), 
     'myValueVALUE::', myValue.val(),
     'mySalePrice.val()::', mySalePrice.val(),
  )
});

And it works fine ,
Is it OK to use it or it needs adjustments ?

Thanks

querySelectorAll returns a NodeList and it has the forEach method on it. getElementsByClassName returns an HTMLCollection and it does not have that method. But you can convert it to an actual array to get access to all the array methods.

const inputs = Array.from(document.getElementsByClassName('unit-purchase-price'));

But I would suggest you use querySelectorAll and querySelector instead of the older methods.


Your code seems fine. As for inpsPurchase[i] I would use this or the second parameter to the callback, you have access to the elements being looped inside the callback so there is really no reason to index into the array to get at the elements.

You do have to be a little careful using the same index with so many different elements/arrays. But I mean it should work just fine as long as they all match up.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.