By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,246 Members | 1,515 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,246 IT Pros & Developers. It's quick & easy.

Generating new HTML on the fly with JS - How can I reference it once the generated?

P: 5
Hello everyone. I have quite the puzzling problem with a script I have been working on lately. I have created a function that can be called to create a new html element (e.g. input, select, div, etc.). It is used as follows:
Expand|Select|Wrap|Line Numbers
  1. addElementToPage("writeroot", "input", "type:button, text:testText, value:testvalue, onclick:test1")
  2.  
The first argument is an ID of the location where the new element it to be appended. The second argument is the type of html element to create. The third argument is the list of any attributes to add to the element.

For the list of arguments I parse them into a 2-dimensional array named "storedArguments". And then I loop through the array and set the attributes for the new element. This is a bit simplified but you get the idea.

The problem comes when I want to set a new event handler. The JS function setAttribute doesn't work for event handlers so you must use attachEvent or addEventListener depending on which browser you use. To do this I once again loop through the storedArguments array and compare each argument and see if it matches anything in my eventHandlers array which has a list of all the event handlers. If it matches one of entries in eventHandlers then AttachEvent (note: this is an actual function in the code, not the built in JS function I referred to earlier) is called. The following is an example of a call to the AttachEvent function.
Expand|Select|Wrap|Line Numbers
  1. AttachEvent("submitButton",'click',test1,false);
  2.  
The function determines which method of attaching and event is needed and then applies the event. Where is says "submitButton" (the ID of the button called "click me") I want to put the variable "elementID" which is the ID of the HTML that was just generated. Unfortunately it doesn't work and give me the error:
Expand|Select|Wrap|Line Numbers
  1. obj has no properties
  2. if (obj.addEventListener){
  3.  
if (obj.addEventListener){ is on line 25. It appears to not be able to find the HTML element that was just generated and appended to the document. If anyone could provide some insight I'd be greatly appreciated. Also, I am very new to javascript so if you happen to see anything that you might change for make more efficient let me know. I am eager to learn everything I can.


Expand|Select|Wrap|Line Numbers
  1.  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"\>
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head>
  5. <title>Adding Nodes</title>
  6. <script type="text/javascript" language="Javascript">
  7.  
  8. var eventHandlers = new Array("onabort", "onblur", "onchange", "onclick", "ondblclick", "onerror", "onfocus", "onkeydown", "onkeypressnload", "onmousedown",  "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onreset", "onresize", "onselect", "onsubmit", "onunload")
  9. var month = new Array("January","February","March","April","May","June","July","August","September","October","November","December"); 
  10. var month1 = new Array("1","2","3","4","5","6","7","8","9","10","11","12"); 
  11. var formIncrement = 0;
  12. var elementID, elementName;
  13.  
  14. function init() {
  15.     formIncrement = formIncrement + 1;
  16.     // AttachEvent(document.getElementById("submitButton"),'click',test1,false);
  17.     addElementToPage("writeroot", "input", "id:testID, name:testName, type:button, text:testText, value:asdfg, onclick:test1, class:test123")
  18.     // newWin();
  19. }    
  20.  
  21. function AttachEvent(obj,evt,fnc,useCapture){
  22.  
  23.     obj = document.getElementById(obj);
  24.  
  25.     if (!useCapture) useCapture=false;
  26.     if (obj.addEventListener){
  27.         obj.addEventListener(evt,fnc,useCapture);
  28.         return true;
  29.     } else if (obj.attachEvent) return obj.attachEvent("on"+evt,fnc);
  30.     else{
  31.         MyAttachEvent(obj,evt,fnc);
  32.         obj['on'+evt]=function(){ MyFireEvent(obj,evt) };
  33.     }
  34.  
  35. // Creates a html element and adds the various attributes to it.
  36. // ID must be set, do not use parenthises when calling a function. 
  37. // All event handler arguments (e.g. onclick, onkeypress) must be lower case.
  38. // EXAMPLE USAGE: addElementToPage("writeroot", "input", "type:button, text:testText, value:testvalue, onclick:test1")
  39. function addElementToPage(locationID, elementType, elementArgs) {    
  40.     elementArgs = removeSpaces(elementArgs); 
  41.     var elementArgs = elementArgs.split(",");
  42.     var argsParsed = new Array();
  43.     var storedArguments = new Array();
  44.  
  45. //alert("elementArgs: " + elementArgs[0]);
  46. //alert("argsParsed: " + argsParsed);
  47. //alert("storedArguments: " + storedArguments);
  48.  
  49.     // Finishes parsing the arguments and stores in a 2-dimensional array
  50.     for(i=0; i <= elementArgs.length-1; i++) { 
  51.         for(j=0; j <= 1; j++) {        
  52.             argsParsed = elementArgs[i].split(":");
  53.             storedArguments[i] = argsParsed;
  54.             if( storedArguments[i][j] == "name") {
  55.                 elementName = storedArguments[i][1] + formIncrement;
  56.                 storedArguments[i][1] = elementName;
  57.             }
  58.             else if( storedArguments[i][j] == "id") {
  59.                 elementID = storedArguments[i][1] + formIncrement;
  60.                 storedArguments[i][1] = elementID;
  61.             }            
  62.         }
  63.     }
  64.  
  65.     try { // For IE
  66.         element = document.createElement('<' + elementType + ' name=\"' + elementName + '\">');
  67.     } 
  68.     catch (e) { // For any other explorer
  69.         var element = document.createElement( elementType);
  70.     }
  71.  
  72.     for(i=0; i <= elementArgs.length-1; i++) {
  73.         if (argsParsed[0] == "name" ) {
  74.             element.setAttribute( "name", elementName );
  75.         }     
  76.         else if (argsParsed[0] == "multiple" || argsParsed[0] == "disabled") {
  77.             element.setAttribute( storedArguments[i][0], storedArguments[i][0]);
  78.         }     
  79.         else {
  80.             element.setAttribute( storedArguments[i][0], storedArguments[i][1] );
  81.         }
  82.     }
  83.  
  84.     // Adds element box to page       
  85.        document.getElementById(locationID).appendChild( element ); 
  86.  
  87.     // Adds any event handlers to the page    
  88.     for(i=0; i <= storedArguments.length-1; i++) {
  89.         for(j=0; j <= eventHandlers.length-1; j++) {
  90.             if (storedArguments[i][0] ==  eventHandlers[j]) {
  91.                 //alert("Element ID: " + elementID);
  92.                 //alert("Element Name: " + elementName);
  93.                 //alert("storedArguments[i]: " + storedArguments[i]);
  94.                 //alert("eventHandlers[j]: " + eventHandlers[j]);
  95.                 AttachEvent(elementID,'click',test1,false);
  96.             }
  97.         }
  98.     }
  99.  
  100.     if( elementType == "select") {
  101.         addOption(elementName,month,month1)   
  102.     }
  103. }
  104.  
  105. function test1(){
  106. alert("test");
  107. }
  108.  
  109. function addOption(selectBoxID, optionNameArray, optionValueArray )
  110. {
  111.     for (var i=0; i < optionNameArray.length-1;++i){
  112.         var optn = document.createElement("option");
  113.         optn.setAttribute( "text", optionNameArray[i] );
  114.         optn.setAttribute( "value", optionValueArray[i] );
  115.         document.getElementById(selectBoxID).options.add(optn); 
  116.     }  
  117. }
  118.  
  119. </script>
  120. </head>
  121. <body>
  122. <form action="" method="post" name="testForm">
  123.     <input type="button" value="Add Element to Page" onclick="init();"/>
  124.     <span id="writeroot"></span>
  125.     <input type="button" value="Click me!" id="submitButton"/>
  126. </form>
  127. </body>
  128. </html>
  129.  
  130.  
Aug 23 '07 #1
Share this Question
Share on Google+
5 Replies


epots9
Expert 100+
P: 1,351
to add a onclick event try using:
Expand|Select|Wrap|Line Numbers
  1. element.onclick = function(){//call method or do something};
  2.  
good luck
Aug 23 '07 #2

P: 5
to add a onclick event try using:
Expand|Select|Wrap|Line Numbers
  1. element.onclick = function(){//call method or do something};
  2.  
good luck

Well that works. However, I am not always going to use "onclick" and will not always call the same function. Can a variable be used in place of the onclick in element.onclick and can I use a variable that has a set function name string set to it within the brackets of function() { }?

Also, is using element.onclick cross browser? What is the difference in using setAttribute, attachEvent/addEventListener, and your method?
Aug 23 '07 #3

epots9
Expert 100+
P: 1,351
the setAttribute works every well (the way it should) in firefox, but ie has some issues with it, so using element.attribute (which is DOM) is cross-browser safe, works in firefox and ie won't complain (for once).

inside the function(){} baskets u can put a function call:
Expand|Select|Wrap|Line Numbers
  1. element.onclick = function(){popup();};
  2. //if u had a function called popup, it would be called when clicked.
  3.  
Aug 23 '07 #4

P: 5
the setAttribute works every well (the way it should) in firefox, but ie has some issues with it, so using element.attribute (which is DOM) is cross-browser safe, works in firefox and ie won't complain (for once).

inside the function(){} baskets u can put a function call:
Expand|Select|Wrap|Line Numbers
  1. element.onclick = function(){popup();};
  2. //if u had a function called popup, it would be called when clicked.
  3.  
Below is essentially what I would like to do (although it currently doesn't work). I want to be able to dynamically set the function that is called as well as the type of event it sets.
Expand|Select|Wrap|Line Numbers
  1. var functionVar = "test1();"
  2. var eventVar = "onmousedown"
  3. element.eventVar = function(){functionVar}
  4.  
Since this doesn't work, is there another way to do this?
Aug 23 '07 #5

P: 5
Well this is the solution I came up with.

Expand|Select|Wrap|Line Numbers
  1. var t = "element." + storedArguments[i][0] + " = function(){" + storedArguments[i][1] + "};"
  2. eval(t);    
  3.  
It works both in IE and Firefox. Now, I seem to remember reading somewhere that eval is not good to use. If that is the case then why should it not be used and is there any alternative to what I'm doing here?
Aug 24 '07 #6

Post your reply

Sign in to post your reply or Sign up for a free account.