Solved

Problem dynamically creating buttons with JavaScript DOM

Posted on 2011-09-28
5
305 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Developer portfolios can be a bit of an enigma—how do you present yourself to employers without burying them in lines of code?  A modern portfolio is more than just work samples, it’s also a statement of how you work.
Dramatic changes are revolutionizing how we build and use technology. Every company is automating, digitizing, and modernizing operations. We need a better, more connected way to work together as teams so we can harness the insights from our system…
HTML5 has deprecated a few of the older ways of showing media as well as offering up a new way to create games and animations. Audio, video, and canvas are just a few of the adjustments made between XHTML and HTML5. As we learned in our last micr…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

695 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