Problem dynamically creating buttons with JavaScript DOM

Hello EE,

I am trying to dynamically create buttons using the JavaScript DOM implementation.

Have a look at the attached code.

<html>
    <head>
        <title>Test!</title>
        <script "text/javascript">
        
            function test()
            {
                // Get the Table
                var theTable = document.getElementById("TestTable");
                
                // Add attributes to the button.
                var DisplayNumber = 0;
                
                // Create the TBODY element.
                var tBody = document.createElement("TBODY");
                theTable.appendChild(tBody);
                
                // Keep Creating Buttons!
                for( var x = 0; x < 5; x++ )
                {
                    // Create the New Row.
                    var newRow = document.createElement("tr");
                    
                    // New Cell and Value.
                    var newCell = document.createElement("td");
                    var newValue = document.createElement("input");
                    
                    // Change Button Attributes.
                    newValue.type = "button";
                    newValue.value = "Press Me!";
                    newValue.onclick = function()
					{ 
						displayPrompt( DisplayNumber ) 
					};
					
					// Append.
                    newCell.appendChild(newValue);
                    newRow.appendChild(newCell);
                    
                    // Append the new row into the TBODY element.
                    tBody.appendChild(newRow);
                    
                    // Increment
                    DisplayNumber++;
                }
            }
            
            function displayPrompt( n )
            {
                // Display prompt.
                alert( n );
            }
            
        </script>
    </head>
    <body onload="test();">
        <table id= "TestTable"></table>
    </body>
</html>

Open in new window


Each button should display a prompt that will display a value. When you press each button from top to bottom, the value will increment (i.e. The top button will display "1", the second will display "2" and the bottom button will display "5").

However, with my current implementation, all the buttons are displaying "5" when the buttons are pressed.

I am probably defining the "onclick" incorrectly. Can anyone help me to create my desired implementation?

I hope this all makes sense.

Thank you very much in advance.
LVL 1
mr_stevieAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
ienaxxxConnect With a Mentor Commented:
i had a problem like that before and was caused by the for loop behaviour combined with dom creation, since the dom objects and properties aren't really created the same time the loop is ran.

try to loop directly on the displaynumber var (i don't understand why you create 'x', since it starts from zero and ends with five just like displaynumber.)

what about creating the buttons serially, outside a loop? it's a dynamic num of buttons or what?

another solution would be to implement a function named 'alertNum', that qccept the parameter to be displayed. Then you can set the onclick values of the buttons with the function call, passing the param.

If it doesn't work, you can try modifying the innerhtml of the td, putting there directly the html code for the input and for the onclick function. since now it's a string concat, it should work


0
 
Kiran SonawaneConnect With a Mentor Project LeadCommented:
Why are you doing so complicated code. Look at below code 3-4 lines.
Test page: http://jsfiddle.net/7X6kG/1/



<html>
<head>
<title>Kiran Test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
    for (var x = 1; x <= 5; x++) {
      $("#TestTable").append('<tr><td><input type="button" id="id_'+x+'"  value="Press Me!"></tr></td>');
    }
    $("#TestTable input:button").live("click",function(){
      alert(($(this).attr("id").split("_")[1]));
    });
    
});

</script>
</head>
<body>
<table id= "TestTable"></table>
</body>
</html>

Open in new window

0
 
mr_stevieAuthor Commented:
The code I've provided is just to encapsulate the idea about a problem I'm having with a larger project; but the concept is there.

Basically instead of "DisplayNumber" being an integer, it is a nodeValue returned from some PHP code I have.

If since the DOM objects aren't created as the loop is run, I guess I could pass the "DisplayNumber" to an attribute like "value" or "id" and pass it through the function later?
0
 
Kiran SonawaneProject LeadCommented:
Not matter whether DisplayNumber  is number string or any other. Jquery has more advantage over javascript. Even DOM object isn't created still you can fire click event using jquery live function. Look at the code.
Not sure what you want exactly.
0
 
mr_stevieAuthor Commented:
It doesn't matter now. I just needed it to be the way I described; which is confusing I know :(

Anyways, knowing that DOM doesn't create the buttons when iterating through the loop, I did the following when giving the button attributes... which seems to work:

 
// Change Button Attributes.
newValue.type = "button";
newValue.id = DisplayNumber;
newValue.value = "Press Me!";
newValue.onclick = function()
{ 
	displayPrompt( this.id ) 
};

Open in new window


0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.