i have three texts namely price,quantity and total. i want the value of total to change with change in quantity i.e total=price*quantity. each time the value of quanity change, the function multiplies it with price and displays the quanity. can somebody send me a javascript code that can do so please.

5 Years
Discussion Span
Last Post by broj1

You probably have a quantity in input field and total somewhere in text (i.e in a div or span element). Both elements should have unique ID so their values can be read by javascript. In addition you should have a button with onclick event attached that fires your javascript function.

Html code:

<input type="text" ID="quantity" /><br />
<input type="button" onclick="calculateTotal()">
<div id ="total"></div>

Javascript code is:

function calculateTotal() {

    // price per unit 
    var price = 30;

    // get input element from DOM
    var inputEl = document.getElementById('quantity');

    // read quantity from the input element (it is read as a string)
    var quantitySting = inputEl.value;

    // convert string value from the form element into integer (or float if needed)
    var quantity = parseInt(quantitySting);

    // calculate total
    var total = price * quantity;

    // get element that displays total from DOM
    var displayEl = document.getElementById('total')

    // display total value in target element
    displayEl.innerHTML = total;

This is more or less basics of getting the value from input and displaying some text in another element on page. You should improve things here (like checking whether entered value is valid, adding currency symbol, or have a select element with preset quantity values and onchange event instead of onclick etc), but in a nutshell this is it.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.