oxygen
oxygen

Reputation: 141

jquery each() iteraton

I want to multiply the input value with p tag when press the button. My html structure is like this:

<div class="table">
    <input class="input" type="text" /> 
    <p>10</p>
</div>

<div class="table">
    <input class="input" type="text" />
    <p>20</p>
</div>

<div class="bill"></div> // the result must be displayed in this tag
<button class="button">Calculate</button>

I use each method to select input elements and it is my jquery structure:

$(function() {
   function calculate()
   {
      $('input.input').each(function(index) {
      var inputValue = $(this).val();
      var valueP = $(this).next('p').text();
      var result = inputValue * valueP;
      $('.bill').text(result);// displays only last multipled result
      console.log(result); // displays all multipled results
   });
   }

   $('.button').click(function() {
       calculate();
   });
});

I achive to multiply input value with p tag but the problem is that only last multiplied input value displays in the class with "bill". But it looks fine with console.log Also, it is fine with "document.write(result)". How can I fix this problem? By the way, someone could say me please how can I sum all multiplied results! Thanks for advance!

Upvotes: 0

Views: 111

Answers (2)

Pragnesh Chauhan
Pragnesh Chauhan

Reputation: 8476

try this demo

function calculate() {
    var result = 0;
    $('input.input').each(function(index) {
        var inputValue = Number($(this).val());
        var valueP = Number($(this).next('p').text());
        result += inputValue * valueP;
//as you were adding here it will each time update the .bill
        console.log(result);
    });
    $('.bill').text(result);
}

$('.button').click(calculate);​

update

demo for showing all calculated result beside adding them

function calculate()
{
   //var result = 0;
  $('input.input').each(function(index) {
  var inputValue = Number($(this).val());
  var valueP = Number($(this).next('p').text());
  var  result = inputValue * valueP;
  $('.bill').append(result+"<br/>");
  console.log(result);
});
}

$('.button').click(calculate);​

Upvotes: 3

suresh gopal
suresh gopal

Reputation: 3156

Please try this:

function calculate() {
    var result = 0;
    $('input.input').each(function(index) {
        var inputValue = Number($(this).val());
        var valueP = Number($(this).next('p').text());
        result += inputValue * valueP;
        $('.bill').append(result);
        console.log(result);
    });

}

$('.button').click(calculate);​

Upvotes: 1

Related Questions