Forum Moderators: open

Message Too Old, No Replies

Code Bloat! Any tips?

Using lots of arrays to pull data, calc it, and push to innerHTML

         

whoisgregg

2:47 am on Nov 4, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I have some javascript I am working on which uses a lot (for me) of different arrays. One of the types of things I do is put the results of all the calculations into <span> tags on the page with code like this:

document.getElementById('rpsSpan_0').innerHTML = ('$'+UPArray[0]+' each');
document.getElementById('rpsSpan_1').innerHTML = ('$'+UPArray[1]+' each');
document.getElementById('rpsSpan_4').innerHTML = ('$'+UPArray[4]+' each');
document.getElementById('rpsSpan_12').innerHTML = ('$'+UPArray[12]+' each');
...snipped many, many lines of the same exact stuff...

There must be a better way to do this that can trim my hundreds of lines of code down to a more manageable quantity. Any pointers for this?

Is it my <span>'s that could be better defined? Right now they look like this:


<span id="rpsSpan_0"></span>

Bernard Marx

7:47 am on Nov 4, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



[pre]
var indices = [0,1,4,12];
for(var k=0;k<indices.length;k++)
document.getElementById('rpsSpan_'+indices[k]).innerHTML
= '$'+UPArray[indices[k]]+' each';
[/pre]

It may be easier to reference the spans by position (they may not actually need ids).
It's hard to say without seeing a sample of the HTML.

whoisgregg

4:42 pm on Nov 4, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



That code will help me considerably. :D I had trying looping through but couldn't get past this code (don't laugh too much):

for(i=0;i< UPArray.length;i++)
document.getElementById('rpsSpan_[red]i[/red]').innerHTML = ('$'+UPArray[[red]i[/red]]+' each');

I hadn't considered concatenating the loop counter into it. I was hoping it would know which letter i's should be replaced, I guess. lol :)

reference the spans by position (they may not actually need ids).

If I understand you correctly... I decided not to navigate through them as an array of input and span elements because, quite frankly, I wasn't sure at the beginning how I was going to arrange the elements. I was trying to save myself from tracking down and rematching inputs with spans.

I did use that for some of my input validation (for negative numbers and non-numbers), with the code below. I start at i = 1 to 'skip' past the only non-number input on the page.


var textFields = document.getElementsByTagName('input');
for (i = 1; i < textFields.length; i++) {
if (textFields[i].type == "text") {
var val = textFields[i].value;
if (val < 0) {
val = 0;
textFields[i].value = 0;
}
if (isNaN(val)) {
val = 0;
textFields[i].value = 0;
}}}