Solved

Problem dynamically creating buttons with JavaScript DOM

Posted on 2011-09-28
5
302 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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

Preface This is the third article about the EE Collaborative Login Project. A Better Website Login System (http://www.experts-exchange.com/A_2902.html) introduces the Login System and shows how to implement a login page. The EE Collaborative Logi…
Because your company can’t afford for you to make SEO mistakes, you’ll want to ensure you’re taking the right steps each and every time you post a new piece of content. This list of optimization do’s and don’ts can help you become an SEO wizard.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
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).

838 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