Add values from input number types

I have around 40 of these below, all individual and I’m wondering how I can use javascript to take the cost value multiply it by the count, and then add it to a running total amount.

So for instance the first one is £3, but if the user adds 3 on the value, how I do I make that £9 and then add it to a running total.

<div class="flabel">
	<label for="adult-items-trousers">Trousers - £3.00</label>
	<input type="number" name="adult-items-trousers" min="0" max="500" value="0">
</div>
<div class="flabel">
	<label for="adult-items-tshirts">T-shirts - £1.20</label>
	<input type="number" name="adult-items-tshirts" min="0" max="500" value="0">
</div>
<div class="flabel">
	<label for="adult-items-skirts">Skirts - £3.00</label>
	<input type="number" name="adult-items-skirts" min="0" max="500" value="0">

first you need to make the price available to JS. that may be a hidden field, data-* attribute or whatever else works. the remainder is fetching each price-amount pair multiply it and summ it up.

NOTE: the label’s for attribute refers to a field’s id, not its name.

So for starters are we looking at something like this -

<input type="number" name="adult-items-trousers" min="0" max="500" value="0" data-price='3.00'>

If correct, does data-price need to be individual for each input, and could you give me a bit of a starter with adding the price and the value I suppose is it, and then allow that to total up for each input.

The idea is that as they fill the form in, i want to have a number of items area and a total price area, which get instantly updated as a visual feedback.

Then once the customer is happy, they click the submit button and an email is sent to the business owner with a breakdown of the form, with the total number of items and total cost included as well as the customers details.

I have made a start but its not working out

$(document).ready(function() {
$('input.qty_input').keyup(function() { 
  var sum = 0;
  $("qty_input").each(function() {
	  var price = $(this).data("price")
	if (this.value.length && !isNaN(this.value) && !isNaN(price))
        sum += parseFloat(this.value) * parseFloat(price);
    })
	$("#result").html(sum.toFixed(2));
  });  
});
<div id="result"></div>
<input type="number" name="adult-items-shirts" min="0" max="500" value="0" data-price="1.20" class="qty_input">
<input type="number" name="adult-items-trousers" min="0" max="500" value="0" data-price="3.00" class="qty_input">
<input type="number" name="adult-items-tshirts" min="0" max="500" value="0" data-price="1.20" class="qty_input">

There’s a missing dot before the class selector near the .each(). Also note that both the input value and data-price are strings, so isNaN() will always return true here; you’ll have to parse them to float before doing that check. You might actually simplify that to

var $result = $('#result')
var $qtyInput = $('.qty_input')

$qtyInput.change(function() {
  var sum = 0

  $qtyInput.each(function() {
    var value = parseFloat(this.value) || 0
    var price = parseFloat(this.dataset.price) || 0
    sum += value * price
  })

  $result.html(sum.toFixed(2))
})
1 Like

Oh cheers for helpin, I changed it to your code and still no result.

If it helps this is where I’m working, its not live or finished yet as you know, but maybe it helps.

dev area

And this is my code now.

<script>
$(document).ready(function() {
var $result = $('#result')
var $qtyInput = $('.qty_input')

$qtyInput.change(function() {
  var sum = 0

  $qtyInput.each(function() {
    var value = parseFloat(this.value) || 0
    var price = parseFloat(this.dataset.price) || 0
    sum += value * price
  })

  $result.html(sum.toFixed(2))
})
});
</script>
<p>#result is here - <span id="result"></span></p>
<input type="number" name="adult-items-shirts" min="0" max="500" value="0" data-price="1.20" class="qty_input">
<input type="number" name="adult-items-trousers" min="0" max="500" value="0" data-price="3.00" class="qty_input">
<input type="number" name="adult-items-tshirts" min="0" max="500" value="0" data-price="1.20" class="qty_input">

It looks like you forgot to include jQuery. The console says:

Uncaught ReferenceError: $ is not defined

tut, sorry.

Thanks very much, that works a treat.

1 Like

Just one more thing, you know if for example they had 3 as a value and they refreshed the page, it doersnt recognise the 3 is still selected until I change the value of another one. Is there anyway of it always reading the values ie 3 items, or 4 items without waiting for a new change.

Does that make sense

I’m also trying to get the total value, but fcant get the number to echo out

Number of items -: <span id="items"></span>

$(document).ready(function() {
var $result = $('#result')
var $qtyInput = $('.qty_input')
var $items = $('#items')

$qtyInput.change(function() {
  var sum = 0

  $qtyInput.each(function() {
    var value = parseFloat(this.value) || 0
    var price = parseFloat(this.dataset.price) || 0
    sum += value * price
  })

  $result.html(sum.toFixed(2))
  $items.html(value)
})
});

Sure, just give that update function a name and call it on page load:

var updatePrices = function () {
  // etc.
}

$qtyInput.change(updatePrices)
updatePrices()

Im sorry to ask, but do you mean like this -

$(document).ready(function() {
var updatePrices = function () {
var $result = $('#result')
var $qtyInput = $('.qty_input')
var $items = $('#items')
}
$qtyInput.change(updatePrices) {
updatePrices()
  var sum = 0

  $qtyInput.each(function() {
    var value = parseFloat(this.value) || 0
    var price = parseFloat(this.dataset.price) || 0
    sum += value * price
  })

  $result.html(sum.toFixed(2))
  $items.html(value)
})
});

No, more like

var $result = $('#result')
var $qtyInput = $('.qty_input')

var updatePrices = function () {
  var sum = 0

  $qtyInput.each(function () {
    var value = parseFloat(this.value) || 0
    var price = parseFloat(this.dataset.price) || 0
    sum += value * price
  })

  $result.html(sum.toFixed(2))
}

$qtyInput.change(updatePrices)
updatePrices()
1 Like

Thats all fab cheers, I’m nearly done and trying to get the total items out, its a strange one though as the only three inputs that are working are the first three, but for soem reason only the last (third) input on the left is making a difference, as in when I change the first 2 I get no count adding or taking away, and thats only working on the third one, but they are exactly the same.

Number of items -: <span id="items"></span>

$(document).ready(function() {
var $result = $('#result')
var $qtyInput = $('.qty_input')
var $items = $('#items')

var updatePrices = function () {
  var sum = 0
  var vitems = 0

  $qtyInput.each(function () {
    var value = parseFloat(this.value) || 0
    var price = parseFloat(this.dataset.price) || 0
    sum += value * price
	vitems = value
  })

  $result.html(sum.toFixed(2))
  $items.html(vitems.toFixed(0))
}

$qtyInput.change(updatePrices)
updatePrices()
});

You might want to add value to vitems, rather than just setting it to the current value in each iteration.

1 Like

Thank you m3g4p0p, you really have helped me today and carry on now and finish it off

Thought it best to carry on the thread as its the same project.

I want to put the two values I have collected in jquery and put them in the email I need to send to the client once the form is submitted.

So currently this is my form

<form class="form" id="form1" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
**
input type="submit" value="SEND" id="button-blue"/>
</form>

<script>
$(document).ready(function() {
var $result = $('#result')
var $qtyInput = $('.qty_input')
var $items = $('#items')
$('input[type="submit"]').attr('disabled','disabled');

var updatePrices = function () {
  var sum = 0
  var vitems = 0

  $qtyInput.each(function () {
    var value = parseFloat(this.value) || 0
    var price = parseFloat(this.dataset.price) || 0
    sum += value * price
    vitems = value + vitems
  })

  $result.html(sum.toFixed(2))
  $items.html(vitems.toFixed(0))
  if (sum >= 10.00) {
	$(".price-colour").css("color", "green");
	$(".minimum-order span").css("display", "none");
	$(".price-wrapper").css("padding-top", "20px");
        $('input[type="submit"]').removeAttr('disabled');	
	} else {
	$(".price-colour").css("color", "#CC0000");
	$(".minimum-order span").css("display", "inline");
	$(".price-wrapper").css("padding-top", "0px");
        $('input[type="submit"]').attr('disabled','disabled');		
	}
}

$(".price-wrapper").hide(); //hide your div initially
    var topOfOthDiv = $(".navbar-header").offset().top;
    $(window).scroll(function() {
        if($(window).scrollTop() > topOfOthDiv) { //scrolled past the other div?
            $(".price-wrapper").show(); //reached the desired point -- show div
        } else {
		 $(".price-wrapper").hide();	
		}
});

$qtyInput.change(updatePrices)
updatePrices()
});
</script>

$nameErr = $emailErr = $enquiryErr = $telephoneErr = $addressErr = $postcodeErr = "";
$name = $email = $text = $telephone = $address = $postcode = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {

}

So am just wondering how do I post sum and vitems to the php form script to pasds those details then via a php variable to the client

Could you add some hidden inputs in the form, assign them appropriate id values, and then update the updatePrices() function to update those values as well as the displayed ones? Then when you submit the form, those values go with it.

1 Like

Are those data-prices coming from the backend anyway? So you could just calculate the final sums there…

Good idea yes, cheers droopsnoot