PDA

View Full Version : splitting string to add totals



chris_angell
Nov 15th, 2007, 06:40 PM
hello I have a string that relates to the element ID's of input box values.. but these input boxes are created dynamically.

so when the javascript splits the element ID, it calls the value. then i am trying to add these up. but i am getting errors.. errors trying to add up and also if a element doesnt excist some times this may happen...

here is my code

<input id="id1" value="14">
<input id="id3" value="14">

function runCode(){
var result = "id1+1d2+1d3+"
var myString = result;
var mySplitResult = myString.split("+");
var GrandTotal = 0
for(i = 0; i < mySplitResult.length; i++){
var myElement = mySplitResult[i];
var myElementValue = parseInt(document.getElementById(""+myElement+"").value);
GrandTotal += GrandTotal + myElementValue
}
alert(GrandTotal)
}

vtjustinb
Nov 15th, 2007, 06:57 PM
Why not give them a specific class and not care about what their ID is?



function sumInputs() {
var inputs = document.getElementsByTagName('input');
var targetClass = 'to-sum';
var total = 0;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].className == targetClass)
total += parseInt(inputs[i].value);
}
alert(total);
}


That way you could just add the class to the inputs (<input class="to-sum" value="14" /> and not worry about the ids.

Worth noting some libraries offer this type of element narrowing (fetching all elements of a certain class) for free. Prototype for example does and would slim down that logic.

shyam
Nov 15th, 2007, 07:42 PM
function runCode(){
var result = "id1+1d2+1d3+"
var myString = result;
var mySplitResult = myString.split("+");
var GrandTotal = 0
for(i = 0; i < mySplitResult.length; i++){
var myElement = mySplitResult[i];
var myElementValue = parseInt(document.getElementById(""+myElement+"").value);
GrandTotal += GrandTotal + myElementValue
}
alert(GrandTotal)
}
are u sure about the line in red?

and u can check the presence of an input by simply checking


if ( !!document.getElementById(myElement) ) {
// element with id exists
}

vtjustinb has given a much cleaner solution see if u can use that