...

View Full Version : Button click increments <div id=id0> etc



Prime8
10-11-2011, 03:43 AM
Hello, I am working on a tool for hardware quoting, I'm currently trying to add a button for adding line items to the quote.

Here is what I currently have:
The HTML:

<html>
...
<input type="button" id="sbutt" onclick="buttinc()" value="Click Me" />
<div id="txtarea"></div>
...
</html>
The script:


vbutt = 0
function buttinc()
{
var buttona = document.getElementById("txtarea");
if (vbutt<100)
{
buttona.innerHTML="<div id='newdiv" + vbutt + "'></div><br />";
var buttb = document.getElementById("newdiv"+vbutt);
buttb.innerHTML = "some text" + vbutt + "close tags and stuff";
vbutt = vbutt + 1;
}
}

Now, it is sort of working the way I expect. When the button is clicked, it creates the new div, starts the id at 0, and increments the div id each time the button is pressed afterwards.

It also displays the text (buttb.innerHTML) in the new div. However, it only increments the id of the same div, it doesn't create a new div under the first one.

What I am hoping for is:
click 1 : <div id="newdiv0">0</div>
click 2 : <div id="newdiv1">1</div>
click 3 : <div id="newdiv2">2</div>
etc

What it is doing:
click 1 : <div id="newdiv0">0</div>
click 2 : <div id="newdiv1">1</div> (newdiv0 disappears)
click 3 : <div id="newdiv2">2</div> (newdiv1 disappears)

What am I missing? Any help is appreciated.

Old Pedant
10-11-2011, 04:05 AM
You are doing

buttona.innerHTML="..."

So EACH TIME you are completely replacing the entire contents of buttona.

In any case, this is a bad way to do it.

Try it the modern way:


vbutt = 0
function buttinc()
{
if ( vbutt >= 100 ) return;

var div = document.getElementById("txtarea");

var newdiv = document.createElement("div");
newdiv.id = "newdiv" + vbutt;
newdiv.innerHTML = "some text " + vbutt + " close tags and stuff";

div.appendChild( newdiv );
div.appendChild( document.createElement("br") );

++vbutt;
}

Prime8
10-11-2011, 04:33 AM
That's really cool, thanks!

I didn't know you could write elements/attributes like that.

Old Pedant
10-11-2011, 05:37 AM
That's the preferred way. Actually, can pretty much avoid innerHTML completely, but I don't see anything wrong with putting plain text into innerHTML.

But if you are curious:


<html><head><script>
vbutt = 0
function buttinc()
{
if ( vbutt >= 100 ) return;

var div = document.getElementById("txtarea");

var newdiv = document.createElement("div");
newdiv.id = "newdiv" + vbutt;
newdiv.appendChild(
document.createTextNode(
"some text " + vbutt + " close tags and stuff"
)
);

div.appendChild( newdiv );
div.appendChild( document.createElement("br") );

++vbutt;
}
</script>
</head>
<body>
<input type="button" id="sbutt" onclick="buttinc()" value="Click Me" />
<br/>
<div id="txtarea">original txtarea content</div>
</body>
</html>

That's the "more correct" way to do it.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum