Jump to content

Javascript Sum function


Hyperjase

Recommended Posts

Hi all,

 

Trying to get a function going which will add up all the numbers from several drop down boxes.  Here is the code:

 

<?php 
foreach ($_SESSION['topping'] as $value) {
    echo "<tr><td width='30%'>Topping</td><td width='50%'>$value</td><td width='20%'><select name='notopping[$value]'>";
$counter = 1;
while ( $counter <= $_SESSION['cupcake'] ) {
  echo '<option value='.$counter.'>'.$counter.'</option>';
  $counter++;
}

 

When the option value is selected, it will select a number, from either 1 to 36.  This is in a foreach loop as the number of drop down boxes is dynamic - chosen from a number of check boxes.  How would I create a javascript function that when the drop down box is changed, the figures are added together and shown at the side.  I want it to be that it shows the number selected in total.

 

Thanks,

 

Jason

Link to comment
Share on other sites

if i understand correctly you just need to sum the vals from multiple dropdowns, so assign an ID to each dropdown then you can do something like this (excuse little syntax errors)

 

<select name='drop1' id='drop1' onChange='sumSelect()';>
</select>

<select name='drop2' id='drop2' onChange='sumSelect()';>
</select

<select name='drop3' id='drop3' onChange='sumSelect()';>
</select>

<span id="total"></span>

<script type="text/javascript">
function sumSelect() {
  var total = document.getElementById("drop1").val() + document.getElementById("drop2").val() + document.getElementById("drop3").val();
  document.getElementById("total").innerHTML(total);
}
</script>

 

of course you can optimize it by looping through all of your select statements depending on your naming convention, something like jquery could really speed it up if they have all the same class for example.

Link to comment
Share on other sites

with a class you no longer need the onclick, you would just have jquery something like this

 

$(document).ready({
$(".dropdown").change(function() {
var total = 0;
$(".dropdown").each(s,function() {
    total += s.val();
});
$("#total").innerHTML("The Total is " + total);
});
<body>
<span id="total"></span>
</body>

});

Link to comment
Share on other sites

I've been trying the code but Dreamweaver keeps telling me there's an error with this line of code : $(".dropdown").change(function() {

 

I wrapped it inside <script type="text/javascript">##</script> - thats when it spat out the error.

 

Any ideas?  I'm quite out of my depth with jquery.

 

Thanks,

 

Jason

Link to comment
Share on other sites

No need to load jquery just for that:

 

 


<script type="text/javascript">
<!--
Array.prototype.sum = function(){
for( var i=0,sum=0; i < this.length; i++)
{
	if ( typeof this[i] == 'undefined' || parseInt(this[i]) == 'NaN' )
		continue;
	sum += this[i];
}
return sum;
}
var totals = [];
window.addEventListener('DOMContentLoaded', function() {
var selects = document.getElementsByTagName('select');
for( var k=0; k < selects.length; k++ )
{
	// only count selects of certain class?
	// if ( this.className != 'class' ) continue;
	selects[k].uid = k+1;
	selects[k].addEventListener('change', function() {
		totals[this.uid] = parseInt(this.value);
		document.getElementById('total').value = totals.sum();
	});
}
});
//-->
</script>
<select name="test">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="test1">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="test2">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="text" id="total" >

Link to comment
Share on other sites

I also have another problem which I'm not sure how to solve.

 

I have more than one drop down box that needs to show the total.  At the moment, the second set of drop down boxes adds to the first total (which it will logically), but I've tried changing the code to reflect the name of the drop down (by using var selects = document.getElementsByTagName('select.topping');) - but that doesn't work.  The next small issue I can see is that each dropdown is dynamic (<select name='notopping[$value]'>).  So one could be Chocolate, one could be Choc Orange.  So can I associate two different drop down sets with two different counters?

 

Thanks,

 

Jason

Link to comment
Share on other sites

Here's the entire form script (please excuse any syntax stuff - I'm still learning)

 

<form id="nocupcakes" method="post" action="?step=3">
<table width="70%" align="center">
<tr>
<td colspan="3">
Please select how many of each type of Cupcake topping you would like<br />
</td>
</tr>
<?php
foreach ($_SESSION['topping'] as $value) {
    echo "<tr><td width='30%'>Topping</td><td width='50%'>$value</td><td width='20%'><select name='notopping[$value]'>";
$counter = 1;
while ( $counter <= $_SESSION['cupcake'] ) {
  echo '<option value='.$counter.'>'.$counter.'</option>';
  $counter++;
}
echo "</select></td></tr>";
}
echo "<tr><td colspan='3' align='center'>Choices Left: <input type='text' id='total' class='dis' size='2' value='0' />/".$_SESSION['cupcake']."</td></tr>";
if (count($_SESSION['swtopping']) > 0) {
?>
<tr>
<td colspan="3">
<br /><br />Please select how many of each type of sweetie topping you would like<br />
</td>
</tr>
<?php
foreach ($_SESSION['swtopping'] as $value) {
    echo "<tr><td width='30%'>Sweetie topping</td><td width='50%'>$value</td><td width='20%'><select name='noswtopping[$value]'>";
$counter = 1;
while ( $counter <= $_SESSION['cupcake'] ) {
  echo '<option name="noswtopping" value="'.$counter.'">'.$counter.'</option>';
  $counter++;
}
echo "</select></td></tr>";
}
echo "<tr><td colspan='3' align='center'>Choices Left: <input type='text' id='total' class='dis' size='2' value='0' />/".$_SESSION['cupcake']."</td></tr>";
}
?>
<tr><td colspan="3"><hr /></td></tr>
<tr><td colspan="3">Would you like them delivered or would you prefer to collect?</td></tr>
<tr><td colspan="2" align="right">Delivered</td><td><input name="delcol" type="radio" value="delivered" data-bvalidator="required" data-bvalidator-msg="Select delivery or collection please" /></td></tr>
<tr><td colspan="2" align="right">Collection</td><td><input name="delcol" type="radio" value="collected" /><br /></td></tr>
</div><tr><td colspan="3" align="center"><input type="submit" value="Next >>" class="submit" /></td></tr>
</td>
</table>
</form>

 

The Sweetie Topping drop down only appears if any have been selected,  at least one Topping drop down will always show.

 

Thanks for your time,

 

Jason

Link to comment
Share on other sites

  • 3 weeks later...
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.