hami
hami

Reputation: 55

How can i get input values in loop using jquery?

I search more times but not get any idea,

Here is HTML:

       {% for pr in productlist %}
       <div class="grid-container">
          <span>
            <label> {{ pr.productname }} </label>
            <label name="mylist" class="prprice" id="prprice"> {{ pr.price1 }} </label>
          </span>
          <section class="sec">
            <input type="number" name="mylist" class="prnumber" id="prnumber">
          </section>
      </div>
      {% endfor %}

I can get price (id : prprice) one by one in loop via : price = parseFloat($(this).parents('span').find('label:eq(1)').text());

It is my full jQuery also :

$(document).ready(function() 
 {
    $("#tabSum").click(function(){
        var price = 0;
        var number = 0;

        $(".grid-container").each(function() {
            
            price = parseFloat($(this).parents('span').find('label:eq(1)').text());
            
            number = parseFloat($('.sec').find("input[name='mylist']").val()); <-- problem
     });  
 });

My problem is that i want get all number (id : prnumber) elements one by one (like price) but it returned first element only, what is wrong here?

Upvotes: 0

Views: 822

Answers (2)

Frenchy
Frenchy

Reputation: 17007

to avoid looping you could do :

$(document).ready(function() 
 {
    $("#tabSum").click(function(){
       var prices = $("label.prprice").map((i,e) => parseFloat($(e).text())).get();

       var numbers = $("input.prnumber").map((i,e) => parseFloat($(e).val())).get();
     });
 });

so you trap all prices in array prices and all numbers in array numbers in the same order

after if you want to have the result price * number, just loop over array:

  var mult =[]
  for (let i = 0; i < prices.length; i++) {
     if(Number.isNaN(numbers[i]) continue;//avoid NaN values, test for prices too if needed
     mult[i] = prices[i] * numbers[i];
  }

to have sum after

 var sum = mult.reduce((a, b) => a + b );

Upvotes: 1

Thallius
Thallius

Reputation: 2619

You forgot $this so it will always find the first element

$(document).ready(function() 
{
    $("#tabSum").click(function(){
        var price = 0;
        var number = 0;

        $(".grid-container").each(function() {
        
            price = parseFloat($(this).parents('span').find('label:eq(1)').text());
        
            number = parseFloat($(this).find("input[name='mylist']").val()); <-- problem
         });  
     });
});

This should work (untested)

Upvotes: 0

Related Questions