Solved

Problem dynamically creating buttons with JavaScript DOM

Posted on 2011-09-28
5
297 Views
Last Modified: 2012-05-12
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.
0
Comment
Question by:mr_stevie
  • 2
  • 2
5 Comments
 
LVL 10

Accepted Solution

by:
ienaxxx earned 250 total points
ID: 36812903
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
 
LVL 17

Assisted Solution

by:sonawanekiran
sonawanekiran earned 250 total points
ID: 36812911
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
 
LVL 1

Author Comment

by:mr_stevie
ID: 36812935
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
 
LVL 17

Expert Comment

by:sonawanekiran
ID: 36812971
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
 
LVL 1

Author Comment

by:mr_stevie
ID: 36813005
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

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
Why do we like using grid based layouts in website design? Let's look at the live examples of websites and compare them to grid based WordPress themes.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Any person in technology especially those working for big companies should at least know about the basics of web accessibility. Believe it or not there are even laws in place that require businesses to provide such means for the disabled and aging p…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now