Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

regenerate code while incrementing a number 1

Status
Not open for further replies.

nmweb

Technical User
Joined
Jan 30, 2006
Messages
2
Location
CA
Can anyone help?
I'm looking for a script that will generate a similar piece of HTML an unlimited number of times.
A proof of concept should be able to take the following code and regenerate it, while incrementing a serial number. For example:

<input type="text" name="number_of_form_fields"> <-- end user enters value "3"
<input type="text" name="name-1"> <-- three name text fields are displayed, with an incrementing number
<input type="text" name="name-2">
<input type="text" name="name-3">
 
How about this :


Code:
<html>
<head>
<script>

function init()
{
var x = parseInt(document.getElementById("number_of_form_fields").value)

for(var i=1;i<=x;i++)
{
 var t = document.createElement("input");
 t.type="text";
 t.name="name-" + i;
document.getElementById("myForm").appendChild(t)
}
}


</script>
</head>
<body>
<a href="#" onClick="init()">test</a>
<form id="myForm">
<input type="text" id="number_of_form_fields" value="3"><br>
</form>
</body>
</html>

hope this helps

simon
 
What do you do with the output of the function?
Does it update an area on the same page or send it somewhere else?

It is very easy to generate the code dynamically, you just have to determine what the trigger is and where the output goes.


Stamp out, eliminate and abolish redundancy!
 
Here's a quick example using innerHTML - although DOM methods would probably be a better way to do it.
Code:
<html>
<head>
<script type="text/javascript">

function blah(num) {
   var str = "";
   for (i = 1; i <= num; i++) {
      str += i + ' <input type="text" name="name-' + i + '"><br />';
   }
   document.getElementById("blahDiv").innerHTML = str;
}

</script>
</head>
<body>
<form id="blahForm" action="">
   <input type="text" name="number_of_form_fields"><br />
   <input type="button" value="generate textboxes" onclick="blah(document.forms['blahForm'].elements['number_of_form_fields'].value)"><br />
   <div id="blahDiv"></div>
</form>
</body>
</html>

-kaht

How much you wanna make a bet I can throw a football over them mountains?
sheepico.jpg
 
Code:
<html>

<head>
<script>
function populateDiv(val)
{
 if(isNaN(val))
 {
 textboxDiv.innerHTML = "";
 }//end if
 else
 {
  var textboxHTML = "";
  for(var i=1; i<=val; i++)
  {
   textboxHTML += "<input type='text' name='name-"+i+"' /><br />";
  }//end for
  textboxDiv.innerHTML = textboxHTML;
  alert(textboxHTML); //just to show you the source code
 }//end else
}//end function
</script>
</head>

<body>
<input type="text" name="number_of_form_fields" [b]onkeyup='populateDiv(this.value);'[/b]>
<div id='textboxDiv'></div>
</body>

</html>

Is this kind of what you're after?


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O Time, Strength, Cash, and Patience! [infinity]
 
Man, am I slow!!!


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O Time, Strength, Cash, and Patience! [infinity]
 
Thanks folks!
This is my first time using this forum and you have been so helpful and prompt!
Really appreciate it! Hopefully I can help someone out sometime.
 
kaht said:
Here's a quick example using innerHTML - although DOM methods would probably be a better way to do it.
Why would the "DOM methods" be better? I've mentioned it in the past... but innerHTML is supported by all the current generation (and the previous generation) browsers dating back about 5 years.

I mean... consider the number of lines, the speed of running the code, the ease of coding... all those things point to innerHTML being a superior choice [smile]

Sorry for the hijack.

Cheers,
Jeff

[tt]Jeff's Page @ Code Couch
[/tt]

What is Javascript? FAQ216-6094
 
I would think that with their being such a simple bit of code to insert into the document with nothing but dynamically altered names, using innerHTML is a lot less code intensive.
But if you were to add in multiple types of fields perhaps even with opitonal attributes the DOM methods would be a lot more re-usable approach. Instead of having to have the static portions of HTML to insert you just have to know what type of field to create. It would scale much more readily.

For something simple like this I would have used innerHTML.


Stamp out, eliminate and abolish redundancy!
 
Why would the "DOM methods" be better?
It's funny that you ask that because I've kinda been saying it all along as well without any proof. However, just last week one of my coworkers was working on a javascript process for a web application that we're developing that uses a lot of AJAX, and therefore a lot of javascript. This application needed to create new DIVs and set styles for the DIVs and onclick handlers and the like. He was asking for ways to speed it up so I suggested he try DOM methods (he was using innerHTML before). The machine he's doing the development on is a 350 mhz machine so it's the low-end machine we expect to see from our users. He noticed a signifigant increase in speed when using the DOM methods to do the same work that innerHTML had been doing. Of course, this increase in speed is accented highly because of how slow the machine is, but it also gives a good benchmark for how superior using the DOM methods can be.

-kaht

How much you wanna make a bet I can throw a football over them mountains?
sheepico.jpg
 
Some interesting food for thought here. In my experience, several things hold true when running scripts:

1. Firefox is always slower than IE
2. Firefox is always more inconsistent in script timings over multiple runs than IE
3. DOM methods are always slower than using innerHTML

So, with that in mind, I found it interesting that DOM methods have been found to be quicker. With this thread in mind, I came up with the following script:

Code:
<html>
<head>
	<script type="text/javascript">
	<!--

		function createInputsUsingDOM(numberToCreate) {
			var frm = document.getElementById('myForm');
			for (var loop=0; loop<numberToCreate; loop++) {
				var newElement = document.createElement('input');
				newElement.type = 'text';
				newElement.name = 'name-' + (loop+1);
				frm.appendChild(newElement);
			}
		}

		function createInputsUsingInnerHTML(numberToCreate) {
			var frm = document.getElementById('myForm');
			var s = '';
			for (var loop=0; loop<numberToCreate; loop++) {
				s += '<input type="text" name="name-' + (loop+1) + '">';
			}
			frm.innerHTML = s;
		}

		onload = function() {
			var timeStart = new Date();
			//createInputsUsingDOM(100);
			//createInputsUsingInnerHTML(100);
			var timeEnd = new Date();
			alert('Time taken: ' + (timeEnd.getTime() - timeStart.getTime()));
		}

	//-->
	</script>
</head>
<body>
	<form id="myForm">
	</form>
</body>
</html>

The relevant method is uncommented, then the number of iterations set. Then, the page was loaded, and refreshed after noting down each time.

I didn't know what the average number of form elements to be created was, so I tried several tests - with 100 elements, and with 10,000 elements. I ran each test 5 times, in both Firefox and IE. I found my previous 3 observations to hold true. All timings are in msecs:

100 elements, Firefox (DOM Method)
140, 109, 141, 109, 125

100 elements, IE (DOM Method)
16, 16, 0, 0, 15

10,000 elements, Firefox (innerHTML Method)
109, 93, 93, 94, 93

10,000 elements, IE (innerHTML Method)
0, 0, 0, 16, 0

However... something bugged me. The fact that kaht's colleague managed to get DOM methods to be significantly faster than innerHTML, when I've always experienced it the other way around (on many PCs with varying clock speeds).

So... I added another function:

Code:
function createInputsUsingInnerHTML2(numberToCreate) {
	var frm = document.getElementById('myForm');
	for (var loop=0; loop<numberToCreate; loop++) {
		frm.innerHTML += '<input type="text" name="name-' + (loop+1) + '">';
	}
}

This one appended to the innerHTML of the form, rather than setting it in one go. The time? Well... let's just say that I managed to leave it running, go and watch an entire episode of Stargate SG1, and start watching another episode before it returned. The final time: 3420375 msecs, or 57 minutes.

I'm not saying that innerHTML will always be slower... nor am I saying that my tests are conclusive for all systems or all browsers... but they certainly re-inforce my prior observations, and those I suspected I would find.

Hope this helps,
Dan

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Hmm..... that's very interesting Dan. I'll have to go see what my co-worker was working on that showed the DOM methods with better results. I know it involved creating a <div> and <input type="checkbox">, and setting some styling to the background color of the <div>.

-kaht

How much you wanna make a bet I can throw a football over them mountains?
sheepico.jpg
 
Apologies - I posted the wrong timings for two of those result sets, and only posted half of the timings anyway. Doh! (well - it was very late!)

Here are all the correct timings:

100 elements, Firefox (DOM Method)
140, 109, 141, 109, 125

100 elements, IE (DOM Method)
16, 16, 0, 0, 15

100 elements, Firefox (innerHTML Method)
109, 93, 93, 94, 93

100 elements, IE (innerHTML Method)
0, 0, 0, 16, 0

10,000 elements, Firefox (DOM Method)
38576, 35953, 107312, 53016, 103031

10,000 elements, IE (DOM Method)
62360, 61625, 61953, 62157, 61828

10,000 elements, Firefox (innerHTML Method)
10688, 48313, 11453, 43172, 11031

10,000 elements, IE (innerHTML Method)
4129, 4625, 4640, 4891, 4750

The observsations remain unaltered. And luckily I didn't have to watch another episode of SG1 ;-)

Dan

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Dan,

Very well thought-out, informative, and educational.

Have one, on me!

Dave


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O Time, Strength, Cash, and Patience! [infinity]
 
I should set up a PayPal address for dontations
I thought your boss paid for your TekTipping? [smile]

Thanks for following up on this, Dan - it confirms my own assumptions (will be keen to see what kaht's colleague's code was doing - but different scenarios always have different solutions).

The timing differences between IE and FF are a bit surprising - the actual speed differences between the two... I didn't think FF was so slow!

Cheers (to the OP for letting us take over - again),
Jeff

[tt]Jeff's Page @ Code Couch
[/tt]

What is Javascript? FAQ216-6094
 
I found out what he was doing. Run this test and you'll see the results are astonishing:

Code:
<html>
<head>
    <script type="text/javascript">
    <!--

        function createInputsUsingInnerHTML(numberToCreate) {
            var frm = document.getElementById('myForm');
            var s = '';
            for (var loop=0; loop<numberToCreate; loop++) {
                s += '<input type="text" name="name-' + (loop+1) + '">';
            }
            frm.innerHTML = s;
        }

        function createInputsUsingInnerHTMLnoString(numberToCreate) {
            var frm = document.getElementById('myForm');
            frm.innerHTML = '';
            for (var loop=0; loop<numberToCreate; loop++) {
                frm.innerHTML += '<input type="text" name="name-' + (loop+1) + '">';
            }
        }

        onload = function() {
            var timeStart = new Date();
            //createInputsUsingInnerHTML(1000);
            //createInputsUsingInnerHTMLnoString(1000);
            var timeEnd = new Date();
            alert('Time taken: ' + (timeEnd.getTime() - timeStart.getTime()));
        }

    //-->
    </script>
</head>
<body>
    <form id="myForm">
    </form>
</body>
</html>

The DOM methods he ended up going with were a bit different from yours as well. He was at first using createElement to make the new divs, but he found he could speed things up by creating the first div, using cloneNode on that div, and just changing the appropriate attributes (id, background-color, etc). It looks like he needs to overhaul the way he was using innerHTML tho, because it's obviously the better way to go.

-kaht

How much you wanna make a bet I can throw a football over them mountains?
sheepico.jpg
 
Well... if nothing else, hopefully your colleague's code will benefit from all this [smile]

It's natural to use += on innerHTML like that... I certainly would (for no reason). Just goes to show that some ways really can be more effective than others!

Cheers,
Jeff

[tt]Jeff's Page @ Code Couch
[/tt]

What is Javascript? FAQ216-6094
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top