Javascript: Update price when quantity changes

javascript calculate price on quantity
javascript onchange calculate total quantity price demo

I am new to javascript and I have been working on this for 4 days now and I haven't made any progress. I have tried a bunch of different options. I saw an example like mine that worked...but it isn't working for me. :( I am trying to have the price adjust as the quantity of tickets changes. Below is the javascript and below that is the html. Any assistance is much appreciated! Thank you!

document.getElementById("totalTicketCost").value = 0 + "." + 00;

function ticketCost()


{

var ticketCost = 5.5;

var inputTicketQuantity = document.getElementById("inputTicketQuantity").value;

var totalTicketCost = parseFloat(ticketCost) * inputTicketQuantity;



if (!isNaN(totalTicketCost))





document.getElementById("totalTicketCost").innerHTML = totalTicketCost;



}

    <form onsubmit="" ="return alertDetails()" id="formPurchaseTickets" enctype="text/plain" method="post" action="mailto:cmst388@xyz.com">
        <h1>Ticket Purchasing Form</h1>
        <p class="alert">Act fast! This transaction must be completed in <span id="timer"></span> minutes.</p>
        <div class="field">
            <label class="required">How many tickets would you like to purchase?</label>
            <input id="inputTicketQuantity" tabindex="1" required type="number" value="0" name="ticket-quantity" min="1" max="3" step="1" title="You can only buy between 1 and 3 tickets">
            $<span id="totalTicketCost">0.00</span>
        </div>

        <div id="contactInfo" style="display:none;">
            <div class="field">
                <label class="required">Name:</label>
                <input required name="name" tabindex="2" type="text" placeholder="Enter name" pattern="[a-zA-Z\s]+" title="Enter only letters. e.g. Smith">
            </div>

            <div class="field">
                <label class="required">E-mail:</label>
                <input id="inputEmail" tabindex="3" required name="email" type="email" placeholder="Enter e-mail address"  onblur="validateEmail()">
            </div>
        </div>
        <hr>

        <input type="submit" tabindex="4" value="Purchase Tickets"> <input type="reset">
    </form>



    <script src="event_registration.js"></script>

</body>

Going with only ES5 here (assuming you're not transpiling at this stage), I did a quick refactor.

var ticketInput = document.getElementById("totalTicketCost");
var inputTicketQuantity = document.getElementById("inputTicketQuantity");
var ticketCost = 5.5;

// Handle the precision up to >= $100
function changeCost( num ) {
  var cost = new Number( parseFloat( num ) * ticketCost );
  var precision = cost.toString().length === 3 ? 3 : 4;
  return cost.toPrecision( precision );
}

inputTicketQuantity.addEventListener('input', function( event ) {
  var value = event.target.value;
  if ( !isNaN( value ) ) {
    ticketInput.innerHTML = changeCost( value );
  }
});

You definitely want to separate out the JS from the HTML as much as possible, avoid the hard to read inline stuff like <form onsubmit="" ="return alertDetails()", should at least be <form onsubmit="return alertDetails()" to fix it.

Update Price Automatically When Quantity Changes on Click – Paul , I added the simple JS code into my js file. Assume your quantity field name is number-323 & price field name is number-450 . So JavaScript code  Re: update price when quantity changes Jun 15, 2016 04:30 AM | umairaslam22 | LINK Hello you need to add a javascript function some thing like that , it will take two parameters multiply quantity by single price item and on return will inject the result in total price textbox.

Add an event listener to you quantity field, and recalculate price.

document.querySelector("#inputTicketQuantity").addEventListener("input", function() {
  let count = this.value;
  calculatePrice(count);
});

Update product price on quantity increase/decrease, As a start I can update the price on the page when the user changes the quantity value but I can't find a Update product price on quantity increase/decrease You're running into a tricky Javascript problem: floats precision. Except I'm trying to make a quantity drop down menu which when you change the quantity the total field is updated I had it working for one, but when I tried to implement it into a for loop (so that when there are more than one item on the page they work separately) nothing happens. Here is my javascript

Your question is not very specific on what you're trying to achieve, but here is functionality to update your total cost as the user adds tickets -

In JS:

function updateCost(count)
{
   var ticketCost = 5.5;
   document.getElementById("totalTicketCost").innerHTML = count * ticketCost;
}

In HTML

<input id="inputTicketQuantity" tabindex="1" required type="number" value="0" name="ticket-quantity" onchange="updateCost(this.value)" min="1" max="3" step="1" title="You can only buy between 1 and 3 tickets">

update price field based on quantity, i need to see update pricing whenever quantity field got updated, you mean changing “price” while you are typing in the “quantity” editor,  It’s an useful topic for me as I am creating an eCommerce Store. I am using ‘WHOLESALE MARKET’ Plugin from “Cedcommerce”. As per your Instant Price Update, I want to update the price instantly when the quantity reaches its Minimum Order of quantity. It can not update for each increament of quantity as you said.

You have to call function ticketCost() on value change event of input quantity textbox

<input id="inputTicketQuantity" onkeydown="ticketCost()" tabindex="1" required type="number" value="0" name="ticket-quantity" min="1" max="3" step="1" title="You can only buy between 1 and 3 tickets">

Or you can add listener in JavaScript as

document.getElementById("inputTicketQuantity").addEventListener("onkeydown", ticketCost);

Add it outside your JavaScript function ticketCost()

Shopping Cart Quantity - JavaScript, Someone can fill up their cart, change the item prices and totals on the now I'm only trying with HTML&CSS and JavaScript as a beginner. The teacher said not to edit the html file, which I assume means I can start the function in javascript? However, that doesn't make sense to me because it's when the number of tickets changes that the monetary value changes. For example, I enter quantity of tickets as "2" and then the price updates to $11. If I put 3 tickets, it's $16.50.

WooCommerce, Basically, I'm trying to replace woocommerce standart "update cart" button with ajax call, which automatically updates order total price when quantity changed. It will be qnt_5 and price will be 99 2) Change JS variable total_items to 5 var total_items = 5; 3) That's all! If you have any questions or suggestions about this "Price Calculation Based On Quantity" tutorial, please use the comments form below! Thank you!

Cart.js, Cart.js is a very small open source Javascript library that makes the addition of powerful Ajax DOM Binding to dynamically render HTML templates as your cart changes. You don't need to worry about ensuring your Ajax requests are synchronous, binding event listeners, or updating the DOM. Item, Price, Qty, Line Price  To change the currency decimal places or the quantity decimal places, you must complete two tasks: You must change the decimal places in the core tables of Microsoft Dynamics GP. You must update fields in Manufacturing in Microsoft Dynamics GP to reflect the change.

Auto update cart after quantity change, But you can try writing the JS code like below- var timeout; jQuery('div.​woocommerce').on('change keyup mouseup', 'input.qty', function(){  Here i am making ajax functionally to update product Quantity in shopping cart. Get code: https://github.com/Hardeepcoder/Laravel-5.3-Tutorials

Comments
  • Where are you getting stuck? You don't seem to be calling the ticketCost() function...
  • Yes. I have tried "onchange="totalTicketCost"", and "onclick". I guess I'm confused where to put the trigger. The teacher said not to edit the html file, which I assume means I can start the function in javascript? However, that doesn't make sense to me because it's when the number of tickets changes that the monetary value changes. For example, I enter quantity of tickets as "2" and then the price updates to $11. If I put 3 tickets, it's $16.50.
  • You can attach listener in JavaScript as well, without changing html code, see my answer
  • Okay. I am packing up my laptop and headed home. I'll give that a try when I get home. Thank you.
  • Thank you all for your help! I marked the correct answer. I still have a lot to learn. I really appreciate you taking the time to answer my question.
  • Ah, thank you so much! This solves the problem. I still have a lot to learn.
  • No problem at all. You'll have some even better tools to use when you get to ES6 / ES2015. : )
  • FYI on my own response that I'm noticing - var cost = Number() not var cost = new Number()
  • Only use let when you want to warn readers of your code that you're going to reassign the variable. Otherwise, always use const.
  • let question author desides by yourself how to do better in his cace