473,771 Members | 2,372 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

5 New Member
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 "storedArgument s". 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 addEventListene r 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 "submitButt on" (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.addEventLi stener){ 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
5 2226
epots9
1,351 Recognized Expert Top Contributor
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
dwmartin18
5 New Member
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/addEventListene r, and your method?
Aug 23 '07 #3
epots9
1,351 Recognized Expert Top Contributor
the setAttribute works every well (the way it should) in firefox, but ie has some issues with it, so using element.attribu te (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
dwmartin18
5 New Member
the setAttribute works every well (the way it should) in firefox, but ie has some issues with it, so using element.attribu te (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
dwmartin18
5 New Member
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

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

Similar topics

17
2138
by: flupke | last post by:
Hi, i create my GUIs mainly via wxGlade. However when you start of to program and want to do some rearranging to the gui, wxglade overwrites your file and you've got to put your own code back in. I think i can work around that (at least a bit) by making a second file that imports the gui generated by wxglade and make classes that extend the original ones. For instance i could have a class MainForm that extends the wxFrame
1
5279
by: Jason Madison | last post by:
We sometimes get very large databases that we want to cut down to use for testing. The information is all related to a central accounts table. The way I thought of doing this is to grab all the foreign constraints and turn them into cascade delete constraints, then delete as many accounts as I want. After this I will restore the constraints back to their original state.
6
5547
by: Poul Møller Hansen | last post by:
I have made a stored procedure, containing this part for generating a unique reference number. SET i = 0; REPEAT SET i = i + 1; SELECT RAND() INTO reference FROM SYSIBM.SYSDUMMY1; SET p_reference = ref_prefix || SUBSTR(CAST(reference AS CHAR(12)),3);
8
1473
by: Lars Netzel | last post by:
Hey! I wrote a message yersterday and got some good answers and have now managed to generate a nice image. The problem is that it's all generated in an Images.Aspx file and I don't really want that. I am writing a WebControl Library and I want to generate everything from there... In the Render Sub of the Control I output some HTML and there I need to reference to a file in the <img> element, is there anyway to NOT have to point to a...
3
1894
by: daniele.balducci | last post by:
Hi All, I'm generating XLS files from ASP(.Net) code using the usual code chunks ... Response.ContentType = "application/vnd.ms-excel" Response.AppendHeader("Content-Disposition", "attachment; filename=""" & NomeFile & """") Response.Flush() Response.write("<table border=""1"" .....
2
1252
by: R.A.M. | last post by:
Hello, I am learning .NET 2.0. I need to learn how to create documentation from /// comments. I downloaded sample project XMLsample from Web and I generated XML documentation XMLsample.xml: <?xml version="1.0"?> <doc> <assembly> <name>XMLdoc</name> </assembly>
4
1193
by: Alex Maghen | last post by:
I want to create an ASP.NET class which generates some client-side HTML objects on a page with the following rules: 1. Only generate these objects from the class if they haven't already been inserted by another instantiation of this class. So if the obejcts have already been inserted, determine that this is the case and don't do it again. 2. Insert these HTML objects at the very end of the <BODYof the page, preferably without the...
9
11937
by: Cesar | last post by:
Hello there, A java programmer sent me a wsdl file, which I have to use to consume his web methods. When I run the wsld.exe tool to generate the class' code, I get the following message: CODEGEN: The operation binding 'getAvaluos' from namespace 'urn:m15.AvaluosPortType' was ignored. The combination of style=rpc with use=literal is not supported.
26
7915
by: bilgekhan | last post by:
What is the correct method for generating 2 independent random numbers? They will be compared whether they are equal. What about this method: srand(time(0)); int r1 = rand(); srand(rand()); int r2 = rand(); bool f = r1 == r2;
0
10260
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10038
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7460
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6712
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2850
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.