#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    9
    Rep Power
    0

    Getting Button Id of ON TH FLY buttons


    This is my code to create a set of 10 buttons vertically.


    Code:
    <!DOCTYPE html>
    <html>
    <body>
    <script>
    
    function myFunction()
    {
    for(i=0;i<10;i++)
    {
    var btn=document.createElement("BUTTON");
    var t=document.createTextNode("JOIN");
    
    document.body.appendChild(btn);
    btn.appendChild(t); 
    
    document.write("<br><br>");
    }
    };
    
    </script>
    <body onload="myFunction()">
    </body>
    </html>

    What I want is, How do I get the Id's of each of these 10 buttons, so that I can link 10 different pages to these buttons.

    I am a naive programmer, detailed explanation(+code) will be apprecialted.
  2. #2
  3. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,692
    Rep Power
    6351
    A) I'm moving this to the javascript forum, since this is not PHP

    B) You create the buttons here:
    var btn=document.createElement("BUTTON");

    You can add attributes like IDs and onclicks to the buttons right there using the btn variable. The JS people will help.
    HEY! YOU! Read the New User Guide and Forum Rules

    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin

    "The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002

    Think we're being rude? Maybe you asked a bad question or you're a Help Vampire. Trying to argue intelligently? Please read this.
  4. #3
  5. A Not To Shabby Code Smurf
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Aug 2008
    Posts
    1,041
    Rep Power
    119
    Example

    Code:
    <!DOCTYPE html>
    <html>
    <body>
    <script>
    
    var pages = new Array("page1.html","page2.html","page3.html","page4.html","page5.html","page6.html","page7.html","page8.html","page9.html");
    
    function myFunction()
    {
    for(i=0;i<10;i++)
    {
    var btn=document.createElement("BUTTON");
    btn.id = "join_btn" + i;
    btn.onclick = function() {
    var getID = parseInt(this.id.split("join_btn")[1]);
    document.location.href = pages[getID-1];
    }
    var t=document.createTextNode("JOIN");
    
    document.body.appendChild(btn);
    btn.appendChild(t); 
    
    document.write("<br><br>");
    }
    };
    
    </script>
    <body onload="myFunction()">
    </body>
    </html>
    Reasoning

    I created an array with 10 keys and gave them html page urls.

    I set-up the btn variable (which is a button element) to dynamically insert a uniquely generated id.

    I created a new variable declared "getID". This variable gets the btn variable's (which is a button element) id (which is currently a string) and then removes the text from the id (aka "split") and uses the number within the id and even though I'm am getting numeric "split" of the original id; it is still in string format. So, then I convert the string into a number. This is to be used later to access the array key(s) from the "pages" array.

    Then I assigned the btn variable (which is a button element) an onclick event and it is to change the document location's href, based on the delegation of "pages" array key.

    Then everything is multiplied 9X, with your for() loop.

    Teacher's Status

    And I'm spent...

    Hope this a good example for you to learn from.

    Sidebar

    If I where you; I would get away from document.write(), as this is susceptible to XSS Injection Vulnerabilities & Attacks.
    Last edited by web_loone08; February 20th, 2013 at 10:02 AM.
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    9
    Rep Power
    0
    Code:
    <style type="text/css">
    .classname {
      -moz-box-shadow:inset 0px 0px 0px 0px #bbdaf7;
      -webkit-box-shadow:inset 0px 0px 0px 0px #bbdaf7;
      box-shadow:inset 0px 0px 0px 0px #bbdaf7;
      background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #79bbff), color-stop(1, #378de5) );
      background:-moz-linear-gradient( center top, #79bbff 5%, #378de5 100% );
      filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#79bbff', endColorstr='#378de5');
      background-color:#79bbff;
      -moz-border-radius:21px;
      -webkit-border-radius:21px;
      border-radius:21px;
      border:2px solid #84bbf3;
      display:inline-block;
      color:#ffffff;
      font-family:Arial;
      font-size:18px;
      font-weight:bold;
      padding:9px 31px;
      text-decoration:none;
      text-shadow:1px 1px 0px #528ecc;
    }.classname:hover {
      background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #378de5), color-stop(1, #79bbff) );
      background:-moz-linear-gradient( center top, #378de5 5%, #79bbff 100% );
      filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#378de5', endColorstr='#79bbff');
      background-color:#378de5;
    }.classname:active {
      position:relative;
      top:1px;
    }
    
    </style>
    <a href="#" class="classname">my button</a>

    I have this above css file.

    HOW do I apply this CSS to my dynamically created buttons? I am using the same javascript as answered above.
  8. #5
  9. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,692
    Rep Power
    6351
    Where his code contains btn.onclick and btn.id, use btn.class.
    HEY! YOU! Read the New User Guide and Forum Rules

    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin

    "The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002

    Think we're being rude? Maybe you asked a bad question or you're a Help Vampire. Trying to argue intelligently? Please read this.
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    9
    Rep Power
    0
    for(i=0;i<10;i++)
    {
    var btn=document.createElement("BUTTON");
    btn.id = "join_btn" + i;

    1 Code:
    btn.class = "classname";


    btn.onclick = function() {
    var getID = parseInt(this.id.split("join_btn")[1]);
    document.location.href = pages[getID-1];
    }

    This way? It didnt work..
  12. #7
  13. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2009
    Posts
    284
    Rep Power
    255
    Hopefully this information may help you learn the basics of the DOM and JavaScript. Don't worry too much about lib- as it uses advanced JavaScript techniques to make DOM events and closure easy for you so you don't need to think about browser compatibility or functional programming.

    lib() takes an element- such as those created via createElement(), or those referenced via getElementById() or document. For example, document.body is an element, and document.createElement('button') is an element as well. We refer to these 'elements' as DOM elements- as they are elements of the DOM.

    You require the ability to set data to DOM elements. Setting the ID is not a good idea- every ID in the HTML document must be unique. Therefore, dynamically adding IDs is not very smart. So, instead, we add a property using set, where we will later use get to retrieve that data. The data added via set and get (provided by lib()), is not stored on the HTML attribute. So setting a property named 'id' via btn.set() will NOT set btn.id- but will set the data variable inside of lib() via closure. Closure is an useful (and perhaps relatively advanced) functional idea- just know that setting properties using set() is not the same as using setAttribute or setting the property on the object (or DOM element) directly.

    This allows us to set an 'id' property without worrying about unique keys or anything. A similar approach is necessary if we would like to set 'name' or many other properties without accidentally breaking the HTML document.

    Hope this is helpful!!:
    JavaScript Code:
    <!doctype html>
    <html>
    <head>
    	<title>Hello</title>
    	<style>
    		.btn {
    			background: red;
    		}
     
    		.btn:hover {
    			background: pink;
    		}
     
    		.btn:active {
    			background: darkred;
    		}
    		p {
    			margin: 0;
    		}
    	</style>
    	<script>
    		var lib = function lib (e) {
    			/**
    				Simple library injecting functionality into an element.
     
    				A 'listen' method is provided for adding events in a
    				simple and uniform way across different browsers.
     
    				A 'set' method is provided for adding properties to
    				elements without affecting the attributes if they exist.
     
    				A 'get' method is provided for referencing properties
    				set via 'set' method. 'get' will not grab data from an 
    				element's attributes or properties not defined via 'set'
    				method.
     
    				That's it. Pass in a DOM element to lib and that element
    				may use these methods. 
     
    				lib returns the element.
    			**/
    			// Create an empty object to store data.
    			var data = {};
     
    			// Create a listening method for events:
    			e.listen = function listen(type, f) {
    				var uni = function uni (evt) {
    					return f.call(e, evt || window.event);
    				};
    				if (e.addEventListener) {
    					e.addEventListener(type, uni, false);
    				} else if (e.attachEvent) {
    					e.attachEvent('on' + type, uni);
    				} else {
    					e['on' + type] = uni;
    				}
    				return e;
    			};
     
    			// Create a set method for setting data on elements:
    			e.set = function store(name, value) {
    				data[name] = value;
    				return e;
    			};
     
    			// Create a get method for getting data from elements:
    			e.get = function get(name) {
    				return data[name];
    			};
     
    			// Return the element:
    			return e;
    		};
    	</script>
    </head>
    <body>
    	<h1>Hello, world.</h1>
    	<script>
    		// Create a function for adding buttons:
    		function addBtn () {
    			// create some elements
    			var p = document.createElement('p');
    			var btn = document.createElement('button');
    			var t = document.createTextNode('JOIN');
     
    			// Add class to btn
    			btn.className = 'btn'
     
    			// Append text to btn:
    			btn.appendChild(t);
     
    			// Append btn to p:
    			p.appendChild(btn);
     
    			// Append p to body:
    			document.body.appendChild(p);
     
    			// return the btn:
    			return btn;
    		}
     
    		// Create a function to nest our program:
    		function myFunc () {
    			var i;
    			var btn;
    			// Create a function to execute when the btn is clicked:
    			// Note 'this' is the clicked element -
    			// - even in IE (thanks to lib.listen)
    			var btnClick = function btnClick (e) {
    				alert("Hello From Btn: " + this.get('id') + "!");
    			};
    			for (i = 0; i < 10; i += 1) {
    				// create & extend the added btn with lib.
    				btn = lib(addBtn()); 
     
    				// set an internal id to 'i'
    				btn.set('id', i);
     
    				// listen to 'click' events on this button.
    				btn.listen('click', btnClick); 
    				// When the button is clicked, run 'btnClick' function.
    			}
    		}
     
    		// Run myFunc() to execute our program:
    		myFunc();
    	</script>
    </body>
    </html>
    Last edited by s-p-n; February 25th, 2013 at 11:30 AM.
    - The Wise Guy
  14. #8
  15. CSS & JS/DOM Adept
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jul 2004
    Location
    USA (verifiably)
    Posts
    20,122
    Rep Power
    4258
    Originally Posted by ManiacDan
    Where his code contains btn.onclick and btn.id, use btn.class.
    You mean "btn.className". "class" is a reserved keyword.
    Spreading knowledge, one newbie at a time.

    Check out my blog. | Learn CSS. | PHP includes | X/HTML Validator | CSS validator | Common CSS Mistakes | Common JS Mistakes

    Remember people spend most of their time on other people's sites (so don't violate web design conventions).

IMN logo majestic logo threadwatch logo seochat tools logo