Anna A.
Anna A.

Reputation: 65

Update a price field on page load

i'm trying to do a function activate on load page, this function is to get a number value in "input#quantity" and calculate "input.final-price" on page load activating function currentPrice. But on page load is not updating the field when the page load.

function currentPrice() {
  var priceProduct = parseFloat($.trim($('span.price').html().replace(",", "").replace("$", "")));	
  var convertion = ((priceProduct)/100).toFixed(2);
  var price = parseFloat($("input#quantity").val());
  var total = ((convertion) * (price)).toFixed(2);
  $("input.final-price").val(total);
  }
// Onload
$(document).on("load", "input", currentPrice);

Upvotes: 0

Views: 570

Answers (2)

Conan
Conan

Reputation: 2709

I've made some assumptions about your markup (see demo below); note that the .final-price reference is now an ID (#final-price) rather than a class (as this makes binding up the associated <label> easier).

I've also assumed you want the final price (read-only) to stay updated in the event that a new quantity is entered.

function currentPrice() {
  var priceProduct = parseFloat($.trim($('span.price').html().replace(",", "").replace("$", "")));
  var convertion = ((priceProduct) / 100).toFixed(2);
  var price = parseFloat($("#quantity").val());
  var total = ((convertion) * (price)).toFixed(2);
  $("#final-price").val(total);
}

$(function() {
  // initialise final figure
  currentPrice();
  
  // ensure total is updated each time quantity is changed
  $("#quantity").on("keyup", currentPrice);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="price">$38,000</span>

<label for="quantity">Quantity</label>
<input id="quantity" value="5" />

<label for="final-price">Final</label>
<input id="final-price" readonly />

Upvotes: 0

Chris
Chris

Reputation: 997

You should wait till the document loaded then run your function

$(function(){
    currentPrice();
});

The above is shorthand for $(document).ready()

Upvotes: 1

Related Questions