1

I have input :

<form>
  <input class="total" type="text" value="" readonly="readonly" />
</form>

And div :

<div class="product">
  <figure>
    <img src="img/1.jpg" alt="product 1" />
    <!-- Hover -->
    <figcaption>
      <p>Add to input</p>
    </figcaption>
  </figure>
  <p class="descript">Description</p>
  <p class="price">99,00</p>
</div>

Question: How to increase input value by price in every click?

Now I increase only number of clicks.

Fiddle.

3 Answers 3

1

First init your total by 0 :

<input class="total" type="text" value="0" readonly="readonly" />

And every time you click get total value and add product_price value to it, see worked example bellow.

Hope this helps.

    $(".product").click(function() {

        var product_price = parseFloat ( $('.price').text() );
        var total         = parseFloat ( $('.total').val() );

        if( !isNaN( total ) )
        {
            $(".total").val( parseFloat( total + product_price));
        }
    });    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    <input class="total" type="text" value="0" readonly="readonly" />
</form>

<div class="product">
    <figure>
        <img src="img/1.jpg" alt="product 1" />
        <!-- Hover -->
        <figcaption>
          <p>Add to input</p>
        </figcaption>
      </figure>
      <p class="descript">Description</p>
      <p class="price">99,00</p>
    </div>

Sign up to request clarification or add additional context in comments.

Comments

0

How about this one:

$(".product").click(function() {
    if(!$(".total").val()){
   $(".total").val((parseFloat($('.price').text())+1)); 
    }
    else{
          $(".total").val((parseFloat($(".total").val())+1)); 
    }  
}); 

JSFIDDLE

Comments

0

Use parseInt($('.price').html(), 10);

Check this:Updated Fiddle

$(".product").click(function() {
    // pobieranie wartości
    sum += parseInt($('.price').text(), 10);

    // add to input value
    $(".total").val(sum);
});    

7 Comments

What if I have a few divs with different prices?
@ rylko we can answer the question with the help of available codes. The condition which you have told he has to handle by using the id attribute.
Why are you using .html() in this case?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.