By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,934 Members | 1,476 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,934 IT Pros & Developers. It's quick & easy.

Total drop down boxes

P: n/a
Hi all,

I have a page with 5 or 6 drop down boxes, all ranging from 1 to 100.

After each is selected, I need a box that will show a total of all the
results.

So basically, dropdown 1 + dropdown 2 + dropdown 3 = box.

A thousand bonus points if someone can tell me how to make sure the box
doesn't = >100. (These are percentages)

Thank-you very much in advance. If I can return the favor (in any
way), don't hesitate to ask.

Thanks!!!
Aimee

Nov 19 '06 #1
Share this Question
Share on Google+
7 Replies


P: n/a
st*****@gmail.com said the following on 11/19/2006 4:13 PM:
Hi all,

I have a page with 5 or 6 drop down boxes, all ranging from 1 to 100.

After each is selected, I need a box that will show a total of all the
results.

So basically, dropdown 1 + dropdown 2 + dropdown 3 = box.
Did you try reading the group FAQ?

How do I get the value of a form control?:
<URL: http://jibbering.com/faq/#FAQ4_13>

How do I convert a string to a number?
<URL: http://jibbering.com/faq/#FAQ4_21>

sel1 = +document.forms['formName'].elements['select1Name'].value;
sel2 = +document.forms['formName'].elements['select2Name'].value;
sel3 = +document.forms['formName'].elements['select3Name'].value;
sel4 = +document.forms['formName'].elements['select4Name'].value;

var totalValue = sel1 + sel2 + sel3 + sel4;

document.forms['formName'].elements['theTotal'].value = totalValue;
A thousand bonus points if someone can tell me how to make sure the box
doesn't = >100. (These are percentages)
if(totalValue >100){alert('I want your school grade also!!!')}
Thank-you very much in advance. If I can return the favor (in any
way), don't hesitate to ask.
Do I get your homework grade?

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Nov 19 '06 #2

P: n/a
st*****@gmail.com wrote:

Hello,
So basically, dropdown 1 + dropdown 2 + dropdown 3 = box.
Randy has already provided appropriate reference on how to achieve your
task. I shall add some kind of example, so that you can experiment a bit
more - have fun, Elegie.
---

<style type="text/css">
input,select {margin:0 10px;border:1px solid #ddd}
input[type=button] {padding:0 10px}
</style>

<script type="text/javascript">
window.onload = (function(){
var NUMBER=null;
var RESULT=null;

function buildForm(){
var x=document.createElement("form");
x.action="#";
x.onsubmit=new Function("return false");

for(var ii=0,sel=buildSelects();ii<sel.length;ii++) {
if(ii>0)x.appendChild(document.createTextNode("+") );
x.appendChild(sel[ii]);
}

x.appendChild(buildExecButton());
x.appendChild(buildResultBox());
return x;
}

function buildSelects(){
for(var ii=0,sel=[],x; ii<5; ii++){
x=document.createElement("select");
for (var j=0,opt=buildOptions();j<opt.length;j++)
x.appendChild(opt[j]);
sel.push(x);
}
return (NUMBER=sel);
}

function buildOptions(){
for(var ii=0,opt=[],x; ii<=100; ii++) {
x=document.createElement("option");
x.value=ii;
x.appendChild(document.createTextNode(ii+"%"))
opt.push(x);
}
return opt;
}

function buildExecButton(){
var x=document.createElement("input");
x.type="button";
x.value="=";
x.onclick=validate;
return x;
}

function buildResultBox(){
var x=document.createElement("input");
x.type="text";
x.readOnly=true;
return (RESULT=x);
}

function validate(evt){
var sum=0;
for(var ii=NUMBER.length; ii--;)
sum+= +(NUMBER[ii].value);
RESULT.value=sum+"%";
RESULT.style.backgroundColor=sum>100?"#c55":"#5c5" ;
}

return function(){
if(document.body &&
document.body.appendChild &&
document.createElement &&
document.createTextNode
){

if(!(NUMBER && RESULT)){
document.body.appendChild(buildForm());
}

} else {
// location.href="unsupported.html";
}
}
})();
</script>

---
Nov 20 '06 #3

P: n/a

Elegie wrote:
st*****@gmail.com wrote:

Hello,
So basically, dropdown 1 + dropdown 2 + dropdown 3 = box.

Randy has already provided appropriate reference on how to achieve your
task. I shall add some kind of example, so that you can experiment a bit
more - have fun, Elegie.
---
I'm reading through now. Thank-you for the tips, I'll reply with how
it goes!

Nov 20 '06 #4

P: n/a
Randy,

Thank-you for the links! I actually found a suitable clip of code by
googling off of that information.

Being an absolute beginner, I wasn't able to take your code clips and
put it into a usable .html file. This doesn't mean I can't! I just
haven't figured it out yet.

Homework- so you're a comedian as well? ; Thing is, I'm a networking
person- I'm only editing this site because I'm the closest they have to
computer person at the moment :/

Elegie,

Your script did exactly what I asked (thank-you!) but not what I wanted
(my fault!).

In this case, I was able to change the amount of dropdowns by editing
the value "5" under the "buildselects" area, but again, you are way out
of my league. Because the drop downs are all created identically, I
wasn't able to assign a "name" value or add a text label to each.

If I can restate what the end solution should look like:

Dropdown 1 has [select name="1"] and values = [0% to 100%]
Dropdown 2 has [select name="2"] and values = [0% to 100%]
Dropdown 3 (etc)
TextBox 1: [Total of All Dropdowns]

Heck, if I could get this far, I could go to sleep tonight (It's
approaching 4a east coast US).

Idealy though, "Textbox 1" would remain "red" or something until the
value = 100. Or even a line of text next to it that said "this doesn't
equal 100% yet". An alert box won't work because I don't want alerts
coming up while end-users are still selecting dropdowns.

If you guys can help, thank-you- if you can't, no worries. You've
gotten me in the right direction.

Cheers!

PS

Code so far:

<html>
<head>
<title>Autosum DropDown</title>
<script type="text/javascript">
<!-- Begin
function startCalc(){
interval = setInterval("calc()",1);
}
function calc(){
percDone1 = document.autoSumForm.percBox1.value;
percDone2 = document.autoSumForm.percBox2.value;
document.autoSumForm.percBoxX.value = (percDone1 * 1) + (percDone2 *
1);
}
function stopCalc(){
clearInterval(interval);
}
// End -->
</script>
</head>
<body>
<form name="autoSumForm">
Value A
<select name="percBox1" onFocus="startCalc();" onBlur="stopCalc();">
<option</option>
<option value="0">0%</option>
<option value="1">1%</option>
<option value="2">2%</option>
<option value="3">3%</option>
<option value="4">4%</option>
<option value="5">5%</option>
<option value="6">6%</option>
<option value="7">7%</option>
<option value="8">8%</option>
<option value="9">9%</option>
</select>
<br>
Value B
<select name="percBox2" onFocus="startCalc();" onBlur="stopCalc();">
<option</option>
<option value="0">0%</option>
<option value="1">1%</option>
<option value="2">2%</option>
<option value="3">3%</option>
<option value="4">4%</option>
<option value="5">5%</option>
<option value="6">6%</option>
<option value="7">7%</option>
<option value="8">8%</option>
<option value="9">9%</option>
</select>
<br>
Total&nbsp; =&nbsp;
<input type=text name="percBoxX" size="3">%
</form>
</body>
</html>

Nov 20 '06 #5

P: n/a
st*****@gmail.com wrote:

Hello,
Being an absolute beginner, I wasn't able to take your code clips and
put it into a usable .html file. This doesn't mean I can't! I just
haven't figured it out yet.
It still looks like you were able to calculate the result as you wished,
so you may not be really that far from the solution.
In this case, I was able to change the amount of dropdowns by editing
the value "5" under the "buildselects" area, but again, you are way out
of my league. Because the drop downs are all created identically, I
wasn't able to assign a "name" value or add a text label to each.
When creating mass data, one usually considers three different methods:

[1] The first method consists in manually writing the content in the
file, either in the HTML file directly or using some automated method on
a server (like a loop in server pages like ASP, PHP or JSP). The
advantage is that users deprived from javascript on their browser will
still see some content, which will be validated on the server. Although
this method increases the network load, this is the safest one and most
employed in business sites.

[2] The second one consists in writing the mass HTML in a javascript
variable, then document.writing the content of this variable on the
document. Users whose user agent does not have javascript enabled will
see nothing, though. This method is generally compatible with all kind
of javascript-enabled browsers.

[3] The last one consists in using DOM (Document Object Model) methods.
Basically, your document is like a tree of elements (representing the
HTML structure), with parents and siblings. New elements can be created
and inserted into the tree. This is an advanced method of populating
data into a HTML page and I used it in the example since I thought this
could be the one teaching you most. As for method 2, users without
javascript see nothing.

Your not being a web developer means I should have used solution 2; the
example has therefore been changed and should be easier to use (if you
use server pages, just plug in the validating part, keeping on eye on
SELECT event handlers).

If I can restate what the end solution should look like:

Dropdown 1 has [select name="1"] and values = [0% to 100%]
Dropdown 2 has [select name="2"] and values = [0% to 100%]
Dropdown 3 (etc)
TextBox 1: [Total of All Dropdowns]
Idealy though, "Textbox 1" would remain "red" or something until the
value = 100. Or even a line of text next to it that said "this doesn't
equal 100% yet". An alert box won't work because I don't want alerts
coming up while end-users are still selecting dropdowns.
Thanks for your example, it gives a nice hint about what you really
want. To specify a background color, your need to retrieve a pointer to
the element you want to color, then apply the color using
pointer.style.backgroundColor="colorCode". Also, you do not need to use
a timer to have the thing calculated (I guess you did that to solve
cross-browsers issues, however using events work fine).

HTH, and have a nice day.
---

<style type="text/css">
#info {font-size:0.8em;}
input,select {margin:0 10px;border:1px solid #ddd}
</style>

<script type="text/javascript">
// Generating part
var buffer=[];
buffer.push("<form>");
buffer.push("<table>");
buffer.push("<tbody>");
buffer.push(getSelectLine("Label 1", "percBox1"));
buffer.push(getSelectLine("Label 2", "percBox2"));
buffer.push(getSelectLine("Label 3", "percBox3"));
buffer.push(getSelectLine("Label 4", "percBox4"));
buffer.push(getSelectLine("Label 5", "percBox5"));
buffer.push(getResultLine("Total :", "percBoxX"));
buffer.push("<\/tbody>");
buffer.push("<\/table>");
buffer.push("<\/form>");
document.write(buffer.join(""));

function getSelectLine(label, selectName) {
var buffer=[];
buffer.push("<tr>");
buffer.push("<td>");
buffer.push(label);
buffer.push("<\/td>");
buffer.push("<td>");
buffer.push(getSelectHTML(selectName));
buffer.push("<\/td>");
buffer.push("<\/tr>");
return buffer.join("");
}

function getResultLine(label, name) {
var buffer=[];
buffer.push("<tr>");
buffer.push("<td>");
buffer.push(label);
buffer.push("<\/td>");
buffer.push("<td>");
buffer.push("<input type='text' name='"+name+"' size='3' readOnly>");
buffer.push("<span id='info'><\/span>");
buffer.push("<\/td>");
buffer.push("<\/tr>");
return buffer.join("");
}

function getSelectHTML(selectName){
var buffer=[];
buffer.push("<select name='"+selectName+"' "+
"onchange='calculate()' onkeyup='calculate()'>");
for(var ii=0; ii<=100; ii++)
buffer.push("<option value='"+ii+"'>"+ii+"%<\/option>")
buffer.push("<\/select>");
return buffer.join("");
}

// validating part
// make sure names are the ones used in the generating part
function calculate(){
var frm=document.forms[0];
var sum= +frm.percBox1.value +
+frm.percBox2.value +
+frm.percBox3.value +
+frm.percBox4.value +
+frm.percBox5.value ;
frm.percBoxX.value = sum;

if(sum==100) {
frm.percBoxX.style.backgroundColor="#5c5";
document.getElementById("info").innerHTML="";
} else {
frm.percBoxX.style.backgroundColor="#c55"
document.getElementById("info").innerHTML="Total should be 100%!";
}
}
</script>

---
Nov 20 '06 #6

P: n/a
Elegie wrote:
<snip>
<script type="text/javascript">
// Generating part
var buffer=[];
buffer.push("<form>");
buffer.push("<table>");
buffer.push("<tbody>");
buffer.push(getSelectLine("Label 1", "percBox1"));
buffer.push(getSelectLine("Label 2", "percBox2"));
buffer.push(getSelectLine("Label 3", "percBox3"));
buffer.push(getSelectLine("Label 4", "percBox4"));
buffer.push(getSelectLine("Label 5", "percBox5"));
buffer.push(getResultLine("Total :", "percBoxX"));
buffer.push("<\/tbody>");
buffer.push("<\/table>");
buffer.push("<\/form>");
document.write(buffer.join(""));
While joining arrays has performance advantages over multiple calls to
document.write and repeated string concatenation, why this form, with
all the Array method calls, rather than, for example:-

document.write(
[
"<form><table><tbody>",
getSelectLine("Label 1", "percBox1"),
getSelectLine("Label 2", "percBox2"),
getSelectLine("Label 3", "percBox3"),
getSelectLine("Label 4", "percBox4"),
getSelectLine("Label 5", "percBox5"),
getResultLine("Total :", "percBoxX"),
"<\/tbody><\/table><\/form>"
].join("")
);

- and having the array created in its final form and employed in one
statement? Particularly as the array is only used once.

Richard.
Nov 20 '06 #7

P: n/a
Richard Cornford wrote:

Hi,
While joining arrays has performance advantages over multiple calls to
document.write and repeated string concatenation, why this form, with
all the Array method calls, rather than, for example:-

document.write(
[
"<form><table><tbody>",
getSelectLine("Label 1", "percBox1"),
getSelectLine("Label 2", "percBox2"),
getSelectLine("Label 3", "percBox3"),
getSelectLine("Label 4", "percBox4"),
getSelectLine("Label 5", "percBox5"),
getResultLine("Total :", "percBoxX"),
"<\/tbody><\/table><\/form>"
].join("")
);

- and having the array created in its final form and employed in one
statement? Particularly as the array is only used once.
As you've pointed out, there is no technical advantage with the form I
have offered. It is indeed slower and longer than your excellent proposal.

My objective when posting some code consists in solving the problem
exposed, but also in making the original poster progress when they read
and experiment with it; that "tutoring javascript" is part of the fun I
have when participating :) However to have someone progress you have to
assess what level he/she is, and what level he/she wants to reach.

In this case, as I understand it, the original poster isn't a programmer
and I simply thought that this form would better exemplify the use of
the second method I had explained, while keeping expressions simple
enough to not confuse him/her. If he/she expresses some interest in
knowing more about optimizing the final code, then of course I'll be
suggesting lots of ideas (most of which starting where they should : to
the design part).

Kind regards.
Nov 20 '06 #8

This discussion thread is closed

Replies have been disabled for this discussion.