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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dwmartin18
    New Member
    • Aug 2007
    • 5

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

    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:
    [CODE=javascript]
    addElementToPag e("writeroot" , "input", "type:butto n, text:testText, value:testvalue , onclick:test1")
    [/CODE]
    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.
    [code=javascript]
    AttachEvent("su bmitButton",'cl ick',test1,fals e);
    [/code]
    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:
    Code:
    obj has no properties
    if (obj.addEventListener){
    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.


    [CODE=javascript]

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"\>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Adding Nodes</title>
    <script type="text/javascript" language="Javas cript">

    var eventHandlers = new Array("onabort" , "onblur", "onchange", "onclick", "ondblclick ", "onerror", "onfocus", "onkeydown" , "onkeypressnloa d", "onmousedow n", "onmousemov e", "onmouseout ", "onmouseove r", "onmouseup" , "onreset", "onresize", "onselect", "onsubmit", "onunload")
    var month = new Array("January" ,"February","Ma rch","April","M ay","June","Jul y","August","Se ptember","Octob er","November", "December") ;
    var month1 = new Array("1","2"," 3","4","5","6", "7","8","9","10 ","11","12" );
    var formIncrement = 0;
    var elementID, elementName;

    function init() {
    formIncrement = formIncrement + 1;
    // AttachEvent(doc ument.getElemen tById("submitBu tton"),'click', test1,false);
    addElementToPag e("writeroot" , "input", "id:testID, name:testName, type:button, text:testText, value:asdfg, onclick:test1, class:test123")
    // newWin();
    }

    function AttachEvent(obj ,evt,fnc,useCap ture){

    obj = document.getEle mentById(obj);

    if (!useCapture) useCapture=fals e;
    if (obj.addEventLi stener){
    obj.addEventLis tener(evt,fnc,u seCapture);
    return true;
    } else if (obj.attachEven t) return obj.attachEvent ("on"+evt,fn c);
    else{
    MyAttachEvent(o bj,evt,fnc);
    obj['on'+evt]=function(){ MyFireEvent(obj ,evt) };
    }
    }

    // Creates a html element and adds the various attributes to it.
    // ID must be set, do not use parenthises when calling a function.
    // All event handler arguments (e.g. onclick, onkeypress) must be lower case.
    // EXAMPLE USAGE: addElementToPag e("writeroot" , "input", "type:butto n, text:testText, value:testvalue , onclick:test1")
    function addElementToPag e(locationID, elementType, elementArgs) {
    elementArgs = removeSpaces(el ementArgs);
    var elementArgs = elementArgs.spl it(",");
    var argsParsed = new Array();
    var storedArguments = new Array();

    //alert("elementA rgs: " + elementArgs[0]);
    //alert("argsPars ed: " + argsParsed);
    //alert("storedAr guments: " + storedArguments );

    // Finishes parsing the arguments and stores in a 2-dimensional array
    for(i=0; i <= elementArgs.len gth-1; i++) {
    for(j=0; j <= 1; j++) {
    argsParsed = elementArgs[i].split(":");
    storedArguments[i] = argsParsed;
    if( storedArguments[i][j] == "name") {
    elementName = storedArguments[i][1] + formIncrement;
    storedArguments[i][1] = elementName;
    }
    else if( storedArguments[i][j] == "id") {
    elementID = storedArguments[i][1] + formIncrement;
    storedArguments[i][1] = elementID;
    }
    }
    }

    try { // For IE
    element = document.create Element('<' + elementType + ' name=\"' + elementName + '\">');
    }
    catch (e) { // For any other explorer
    var element = document.create Element( elementType);
    }

    for(i=0; i <= elementArgs.len gth-1; i++) {
    if (argsParsed[0] == "name" ) {
    element.setAttr ibute( "name", elementName );
    }
    else if (argsParsed[0] == "multiple" || argsParsed[0] == "disabled") {
    element.setAttr ibute( storedArguments[i][0], storedArguments[i][0]);
    }
    else {
    element.setAttr ibute( storedArguments[i][0], storedArguments[i][1] );
    }
    }

    // Adds element box to page
    document.getEle mentById(locati onID).appendChi ld( element );

    // Adds any event handlers to the page
    for(i=0; i <= storedArguments .length-1; i++) {
    for(j=0; j <= eventHandlers.l ength-1; j++) {
    if (storedArgument s[i][0] == eventHandlers[j]) {
    //alert("Element ID: " + elementID);
    //alert("Element Name: " + elementName);
    //alert("storedAr guments[i]: " + storedArguments[i]);
    //alert("eventHan dlers[j]: " + eventHandlers[j]);
    AttachEvent(ele mentID,'click', test1,false);
    }
    }
    }

    if( elementType == "select") {
    addOption(eleme ntName,month,mo nth1)
    }
    }

    function test1(){
    alert("test");
    }

    function addOption(selec tBoxID, optionNameArray , optionValueArra y )
    {
    for (var i=0; i < optionNameArray .length-1;++i){
    var optn = document.create Element("option ");
    optn.setAttribu te( "text", optionNameArray[i] );
    optn.setAttribu te( "value", optionValueArra y[i] );
    document.getEle mentById(select BoxID).options. add(optn);
    }
    }

    </script>
    </head>
    <body>
    <form action="" method="post" name="testForm" >
    <input type="button" value="Add Element to Page" onclick="init() ;"/>
    <span id="writeroot"> </span>
    <input type="button" value="Click me!" id="submitButto n"/>
    </form>
    </body>
    </html>

    [/CODE]
  • epots9
    Recognized Expert Top Contributor
    • May 2007
    • 1352

    #2
    to add a onclick event try using:
    [code=javascript]
    element.onclick = function(){//call method or do something};
    [/code]

    good luck

    Comment

    • dwmartin18
      New Member
      • Aug 2007
      • 5

      #3
      Originally posted by epots9
      to add a onclick event try using:
      [code=javascript]
      element.onclick = function(){//call method or do something};
      [/code]

      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?

      Comment

      • epots9
        Recognized Expert Top Contributor
        • May 2007
        • 1352

        #4
        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:
        [code=javascript]
        element.onclick = function(){popu p();};
        //if u had a function called popup, it would be called when clicked.
        [/code]

        Comment

        • dwmartin18
          New Member
          • Aug 2007
          • 5

          #5
          Originally posted by epots9
          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:
          [code=javascript]
          element.onclick = function(){popu p();};
          //if u had a function called popup, it would be called when clicked.
          [/code]
          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.
          [code=javascript]
          var functionVar = "test1();"
          var eventVar = "onmousedow n"
          element.eventVa r = function(){func tionVar}
          [/code]
          Since this doesn't work, is there another way to do this?

          Comment

          • dwmartin18
            New Member
            • Aug 2007
            • 5

            #6
            Well this is the solution I came up with.

            [code=javascript]
            var t = "element." + storedArguments[i][0] + " = function(){" + storedArguments[i][1] + "};"
            eval(t);
            [/code]

            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?

            Comment

            Working...