Add elements in script

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • truptidalia
    New Member
    • May 2007
    • 13

    Add elements in script

    Hello Friends,

    I am new on this site.
    I am developing an appi. where I need to add textboxes at runtime in a <div>.

    On one button click, I call the following function (Javascript):
    Code:
    function createDrivePanel() {
        var odiv = document.getElementById('directDIV');
        odiv.innerHTML = "":
        var fromLbl=document.createElement("<label for='drFrom'>Drive From: </label>");
        var toLbl=document.createElement("<label  for='drTo'>Drive To: </label>");
        var fromTxt=document.createElement("<input type='text' id='DriveFromTxt' name='DriveFromTxt' value='' />");
        var toTxt=document.createElement("<input type='text' id='DriveToTxt' name='DriveToTxt' value='' />");
        var getBtn=document.createElement("<input type='button' id='getDirectionsBtn' name='getDirectionsBtn' value='Get Directions' />");
        getBtn.attachEvent("onclick", GetDirections1(DriveFromTxt.text, DriveToTxt.text));
        alert("all elements Inits");  
        odiv.appendChild(fromLbl);
        odiv.appendChild(fromTxt);
        odiv.appendChild('<br>');
        odiv.appendChild(toLbl);
        odiv.appendChild(toTxt);
        odiv.appendChild('<br>');
        odiv.appendChild(getBtn);
        document.getElementById('directDIV').innerHTML = odiv;
    }
    
    function GetDirections1(from, to) {
        
    //    ResultsPanel.Controls.Add("Drive From " + from + "Drive To " + to);
        alert("Drive From " + from + "Drive To " + to); 
    }
    As you can see, the function adds 2 labels, 2 textboxes and 1 button in a <div> element. I also want to call another functin on click of the new created button and henced, event is also atached. But the code is not working.

    I get error. on line var fromLbl=documen t..... Line. It says Expected '.' I can't figure out the problem.

    If you guys can help me figure out the problem, I would be very glad. Any help is appreciated. I need to resolve this ASAP. Hoping to hear from you all experts soon.

    Thanks
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5390

    #2
    as far as i know you cannot use createElement the way you did ... an element is a dom node ... create it first. if you need to set Attributes then you have to use the setAttribute-method. and you may set innerText, innerHTML or create an additional textNode to append text for that element ... example below:

    Code:
    // create the label-node
    var label = document.createElement('label');
    
    // set an symbolic attribute - replace it with the one you need
    label.setAttribute('attrname', 'value');
    
    // create a textnode with 'text' as value
    var label_txt = document.createTextNode('text');
    
    // append textnode to label
    label.appendChild(label_txt);
    
    // now you may append the label wherever you want to your document

    Comment

    • iam_clint
      Recognized Expert Top Contributor
      • Jul 2006
      • 1207

      #3
      IE=Internet Explorer
      FF=Firefox, Opera, Netscape
      Dom works differently in IE than it does FF are you viewing this in FF or IE? also if you need help making it cross-browser compatible reply back.

      Comment

      • truptidalia
        New Member
        • May 2007
        • 13

        #4
        Hi,

        By now, I somehow managed to dispaly the elements. But the events seems ot to be registered i.e. On click of button, nothing happens. Their is no error msg also,

        Updated Code is :
        Code:
            getDirectionsBtn.setAttribute("value", "Get Directions");
        //    getDirectionsBtn.setAttribute("onClick", "GetDirections");
        //    getDirectionsBtn.setAttribute("onClick", "GetDirections()");
            getDirectionsBtn.setAttribute("onclick", "GetDirections(" + fromTxt.value + ", " + toTxt.value +")");
        //    getDirectionsBtn.attachEvent("onclick", "GetDirections(" + fromTxt.value + ", " + toTxt.value +")");
            alert("all elements Inits");  
            dynamicForm.appendChild(fromLbl);
            dynamicForm.appendChild(fromTxt);
            dynamicForm.appendChild(document.createElement("<br>"));
        //    frm.appendChild(toLbl);
            dynamicForm.appendChild(toTxt);
            dynamicForm.appendChild(document.createElement("<br>"));
            dynamicForm.appendChild(getDirectionsBtn);
            odiv.insertBefore(dynamicForm, lbl);    
        //    document.getElementById('directDIV').innerHTML = odiv;
        }
        
        
        function GetDirections(from, to) {
            
        //    ResultsPanel.Controls.Add("Drive From " + from + "Drive To " + to);
        //    alert("Drive From " + document.getElementById('fromTxt') + "Drive To " + document.getElementById('toTxt')); 
            alert("Drive From " + from + "Drive To " + to); 
        }
        You can see, how in different ways I have tried to call the function, with/without prameters. Can anyone tell, y am I not able to call the function of button click.

        One more thing, can I access the text fields value by document.getEle mentById in another function.

        I use IE 6.How Cross Browser compatibility can be managed, I would also like to know about it.

        Thanks

        Comment

        • iam_clint
          Recognized Expert Top Contributor
          • Jul 2006
          • 1207

          #5
          Let me try to answer this all in one post.

          Code:
          getDirectionsBtn.setAttribute("onClick", "GetDirections()");
          Should be
          Code:
          getDirectionsBtn.onClick = GetDirections();
          ok next problem

          accessing these from getElementById

          Yes and no and yes.....

          IE6 you have to create the element like this
          Code:
          var div = document.createElement("<div id=\"Example\" name=\"Example\">");
          in Firefox you have to do it this way
          Code:
          var div = document.createElement("DIV");
          div.id = "Example";
          div.name = "Example";
          so you need to detect the browser and decide which path the creation of the element should take. If you try to use the firefox way in IE it will work but you will not beable to grab the Element by its id (its a known bug) and if you try to use the IE hack in firefox the code will fail and stop.

          Code:
          var browser=navigator.appName
          will get you the browser name.

          Now that being said let me know if you have any more problems.

          Comment

          • gits
            Recognized Expert Moderator Expert
            • May 2007
            • 5390

            #6
            ok ... as a try - set attributes with the corresponding dom-method, i think it should work:

            Code:
            // replace element with the appropriate node
            element.setAttribute('id', 'whateveridyouwant');
            besides that: the appname of a browser is not very reliable ... if you need to detect, whether a browser supports your script or not ... try to detect the abilities of the browser. a common example is the well known creation of a XMLHttpRequest-Object:

            Code:
                
                if (typeof window.XMLHttpRequest != 'undefined') {
                    XMLHTTP = new XMLHttpRequest;
                } else if (typeof window.ActiveXObject) {
                    try {
                        XMLHTTP = new ActiveXObject('Msxml2.XMLHTTP');
                    } catch (ex) {
                        try {
                            XMLHTTP = new ActiveXObject('Microsoft.XMLHTTP');
                        } catch (ex) {
                        }
                    }
                }
            detecting that way ... you should have a working code even when the appname is faked or wrong detected ... or when you try to use version-specific code ... a new version comes up ... its an idea ... and good practice in a lot of our projects ... (note: i think on quirksmode was a very good article for an better explaination than mine :) )

            Comment

            • truptidalia
              New Member
              • May 2007
              • 13

              #7
              Thanks all of you for all this help.

              Eventually, I managed to show the elemetns but the button was not being fired on clik. For that also I got help of someone like you this way -
              Code:
               
                 var getVal=function(){
                      driveFrom=document.forms['dynamicForm'].elements['fromTxt'].value;
                      driveTo=document.forms['dynamicForm'].elements['toTxt'].value; 
                      GetDirections(driveFrom, driveTo);
                  }  //this sets up a function in the same scope as the onclick assignment that will use it.
                  getDirectionsBtn.onclick=getVal;  //this assigns the function to the element.
              Now I am want to remove all elements from the div element except one elemnt that is a label.
              Add also, add a new textarea within the div. The Textarea is not working.

              Code:
               
              function insertText(text) {
                 var d=document.getElementById("directDIV");
                  d.style.visibility="visible";
                   var dynamicForm=document.createElement("form");
                  dynamicForm.setAttribute("id", "dynamicForm");
                  dynamicForm.setAttribute("runat", "server");
                  
                  var textTA=document.createElement("textarea");
                  textTA.setAttribute("id", "textTA");
                  textTA.setAttribute("overflow", "auto");
                  textTA.setAttribute("rows", "30");
                  textTA.innerHTML=text;
              
                  dynamicForm.appendChild(textTA);
                  d.insertBefore(dynamicForm, lbl);  
              }
              Actually, I want this div part to add & remove differnt contents often. Mainly their are 2-3 functionality wher I need to do this. For more reference of what I want to do exactly will find in www.local.live. com site. The left part of the screen changes its contents on Find, Driving Directions etc. I am trying to preform similar things in a single div. Straight away, no parts or expand - collapse style.

              I belive you guys will be able to help me out with this error also. It gives me error on textTA.innerHTM L line.

              Also, give me guidance to remove elements that I have added dynamically except the label id =lbl.

              Thanks a lot
              Hope to hear from you all very soon. Thanks once again for all the help & distinguish bet Firefox & IE elements. How can I confirm that this ste will work on both browsers. Any idea.

              Trupti

              Comment

              • truptidalia
                New Member
                • May 2007
                • 13

                #8
                Originally posted by gits
                detecting that way ... you should have a working code even when the appname is faked or wrong detected ... or when you try to use version-specific code ... a new version comes up ... its an idea ... and good practice in a lot of our projects ... (note: i think on quirksmode was a very good article for an better explaination than mine :) )
                Dear gits,

                What & how will this XMLHTTPrequest object help me in knowing if the scritpt is supported or not? What if it is not supported?

                I understand and appreciate your idea but want to know the Adv, dis adv, features f it over the other way out.

                If anybody can reply this, it would be great.

                Thanks

                Comment

                • gits
                  Recognized Expert Moderator Expert
                  • May 2007
                  • 5390

                  #9
                  ... I mentioned it as an example ... it is besides your originally problem. using a browser-detection that relies on the navigator.appna me may fail in some cases ... due to the fact, that browsers may identify as something they are not ...

                  the example shows how you may create a XMLHttpRequest-Object without the need to ask for the appname ... and you may do that in most cases where you have to use browser-specific code ...

                  hope this makes it more understandable ... the advantages are: you don't need to ask for versions of a browser, or have to adapt your detection code if the appname changes for whatever reason that might be possible ... only ask for the method (ability) you want to use and try to build fallback-options within your code if the method is not available ... that should result in more reliable and robust detection ...

                  I mentioned the quirksmode article too - you find it here:

                  http://www.quirksmode. org/js/support.html

                  Comment

                  • gits
                    Recognized Expert Moderator Expert
                    • May 2007
                    • 5390

                    #10
                    ahhhrg ... and i forgot to mention, that if setAttribute works ... and i think it should ... then you may forget about browser-detection at this point ... until you may createElements and setAttributes the one way :) ... but im not sure about the IE-issue that iam_clint mentioned ... until i only got it to test in IE6 on my mediacenter ... where it works ... please test it in other IEs ... and let me know if it works ... would be interesting to know ...

                    greetings to you and iam_clint ... ;)

                    Comment

                    • iam_clint
                      Recognized Expert Top Contributor
                      • Jul 2006
                      • 1207

                      #11
                      [font=Arial]http://javascript.about.com/library/bliebug2.htm[/font]


                      its been awhile since i've done some create elements it looks like IE has a problem with giving an element a NAME not an ID, which is important to forms. my bad read the article.

                      Comment

                      • gits
                        Recognized Expert Moderator Expert
                        • May 2007
                        • 5390

                        #12
                        Originally posted by iam_clint
                        [font=Arial]http://javascript.about.com/library/bliebug2.htm[/font]


                        its been awhile since i've done some create elements it looks like IE has a problem with giving an element a NAME not an ID, which is important to forms. my bad read the article.
                        hello,

                        sent you a message ... and when you agree with that you might post the code here ... i'm always convinced, that we may avoid browser-detection at this point ... browser-detection IS evil but sometimes not to be avoided. if we may avoid it ... then we should do ... even, when we have to write more lines of standard-compliant-code for that goal ... regular dom-methods will do ... and i think they do well for this problem here.

                        kind regards ...

                        Comment

                        Working...