473,898 Members | 4,913 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Add elements in script

13 New Member
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):
Expand|Select|Wrap|Line Numbers
  1. function createDrivePanel() {
  2.     var odiv = document.getElementById('directDIV');
  3.     odiv.innerHTML = "":
  4.     var fromLbl=document.createElement("<label for='drFrom'>Drive From: </label>");
  5.     var toLbl=document.createElement("<label  for='drTo'>Drive To: </label>");
  6.     var fromTxt=document.createElement("<input type='text' id='DriveFromTxt' name='DriveFromTxt' value='' />");
  7.     var toTxt=document.createElement("<input type='text' id='DriveToTxt' name='DriveToTxt' value='' />");
  8.     var getBtn=document.createElement("<input type='button' id='getDirectionsBtn' name='getDirectionsBtn' value='Get Directions' />");
  9.     getBtn.attachEvent("onclick", GetDirections1(DriveFromTxt.text, DriveToTxt.text));
  10.     alert("all elements Inits");  
  11.     odiv.appendChild(fromLbl);
  12.     odiv.appendChild(fromTxt);
  13.     odiv.appendChild('<br>');
  14.     odiv.appendChild(toLbl);
  15.     odiv.appendChild(toTxt);
  16.     odiv.appendChild('<br>');
  17.     odiv.appendChild(getBtn);
  18.     document.getElementById('directDIV').innerHTML = odiv;
  19. }
  20.  
  21. function GetDirections1(from, to) {
  22.  
  23. //    ResultsPanel.Controls.Add("Drive From " + from + "Drive To " + to);
  24.     alert("Drive From " + from + "Drive To " + to); 
  25. }
  26.  
  27.  
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
May 11 '07 #1
11 1595
gits
5,390 Recognized Expert Moderator Expert
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:

Expand|Select|Wrap|Line Numbers
  1. // create the label-node
  2. var label = document.createElement('label');
  3.  
  4. // set an symbolic attribute - replace it with the one you need
  5. label.setAttribute('attrname', 'value');
  6.  
  7. // create a textnode with 'text' as value
  8. var label_txt = document.createTextNode('text');
  9.  
  10. // append textnode to label
  11. label.appendChild(label_txt);
  12.  
  13. // now you may append the label wherever you want to your document
  14.  
May 11 '07 #2
iam_clint
1,208 Recognized Expert Top Contributor
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.
May 11 '07 #3
truptidalia
13 New Member
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 :
Expand|Select|Wrap|Line Numbers
  1.     getDirectionsBtn.setAttribute("value", "Get Directions");
  2. //    getDirectionsBtn.setAttribute("onClick", "GetDirections");
  3. //    getDirectionsBtn.setAttribute("onClick", "GetDirections()");
  4.     getDirectionsBtn.setAttribute("onclick", "GetDirections(" + fromTxt.value + ", " + toTxt.value +")");
  5. //    getDirectionsBtn.attachEvent("onclick", "GetDirections(" + fromTxt.value + ", " + toTxt.value +")");
  6.     alert("all elements Inits");  
  7.     dynamicForm.appendChild(fromLbl);
  8.     dynamicForm.appendChild(fromTxt);
  9.     dynamicForm.appendChild(document.createElement("<br>"));
  10. //    frm.appendChild(toLbl);
  11.     dynamicForm.appendChild(toTxt);
  12.     dynamicForm.appendChild(document.createElement("<br>"));
  13.     dynamicForm.appendChild(getDirectionsBtn);
  14.     odiv.insertBefore(dynamicForm, lbl);    
  15. //    document.getElementById('directDIV').innerHTML = odiv;
  16. }
  17.  
  18.  
  19. function GetDirections(from, to) {
  20.  
  21. //    ResultsPanel.Controls.Add("Drive From " + from + "Drive To " + to);
  22. //    alert("Drive From " + document.getElementById('fromTxt') + "Drive To " + document.getElementById('toTxt')); 
  23.     alert("Drive From " + from + "Drive To " + to); 
  24. }
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
May 12 '07 #4
iam_clint
1,208 Recognized Expert Top Contributor
Let me try to answer this all in one post.

Expand|Select|Wrap|Line Numbers
  1. getDirectionsBtn.setAttribute("onClick", "GetDirections()");
  2.  
Should be
Expand|Select|Wrap|Line Numbers
  1. getDirectionsBtn.onClick = GetDirections();
  2.  
ok next problem

accessing these from getElementById

Yes and no and yes.....

IE6 you have to create the element like this
Expand|Select|Wrap|Line Numbers
  1. var div = document.createElement("<div id=\"Example\" name=\"Example\">");
  2.  
in Firefox you have to do it this way
Expand|Select|Wrap|Line Numbers
  1. var div = document.createElement("DIV");
  2. div.id = "Example";
  3. div.name = "Example";
  4.  
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.

Expand|Select|Wrap|Line Numbers
  1. var browser=navigator.appName
  2.  
will get you the browser name.

Now that being said let me know if you have any more problems.
May 12 '07 #5
gits
5,390 Recognized Expert Moderator Expert
ok ... as a try - set attributes with the corresponding dom-method, i think it should work:

Expand|Select|Wrap|Line Numbers
  1. // replace element with the appropriate node
  2. element.setAttribute('id', 'whateveridyouwant');
  3.  
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:

Expand|Select|Wrap|Line Numbers
  1.  
  2.     if (typeof window.XMLHttpRequest != 'undefined') {
  3.         XMLHTTP = new XMLHttpRequest;
  4.     } else if (typeof window.ActiveXObject) {
  5.         try {
  6.             XMLHTTP = new ActiveXObject('Msxml2.XMLHTTP');
  7.         } catch (ex) {
  8.             try {
  9.                 XMLHTTP = new ActiveXObject('Microsoft.XMLHTTP');
  10.             } catch (ex) {
  11.             }
  12.         }
  13.     }
  14.  
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 :) )
May 12 '07 #6
truptidalia
13 New Member
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 -
Expand|Select|Wrap|Line Numbers
  1.  
  2.    var getVal=function(){
  3.         driveFrom=document.forms['dynamicForm'].elements['fromTxt'].value;
  4.         driveTo=document.forms['dynamicForm'].elements['toTxt'].value; 
  5.         GetDirections(driveFrom, driveTo);
  6.     }  //this sets up a function in the same scope as the onclick assignment that will use it.
  7.     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.

Expand|Select|Wrap|Line Numbers
  1.  
  2. function insertText(text) {
  3.    var d=document.getElementById("directDIV");
  4.     d.style.visibility="visible";
  5.      var dynamicForm=document.createElement("form");
  6.     dynamicForm.setAttribute("id", "dynamicForm");
  7.     dynamicForm.setAttribute("runat", "server");
  8.  
  9.     var textTA=document.createElement("textarea");
  10.     textTA.setAttribute("id", "textTA");
  11.     textTA.setAttribute("overflow", "auto");
  12.     textTA.setAttribute("rows", "30");
  13.     textTA.innerHTML=text;
  14.  
  15.     dynamicForm.appendChild(textTA);
  16.     d.insertBefore(dynamicForm, lbl);  
  17. }
  18.  
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
May 12 '07 #7
truptidalia
13 New Member
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
May 12 '07 #8
gits
5,390 Recognized Expert Moderator Expert
... 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
May 12 '07 #9
gits
5,390 Recognized Expert Moderator Expert
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 ... ;)
May 12 '07 #10

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

Similar topics

1
1635
by: Howard Jess | last post by:
Apparently, form elements of type <input type="image" src="...> are not included in the form's elements collection. I don't understand why not; according to DOM2, all form control elements in the form are part of the elements collection. Further, this element doesn't appear in the (DOM0) document.images collection either; so it's really not well-accounted for.
6
1287
by: kirku | last post by:
hello, i'm not very good with english i will explain my problem wit an exemple: // i have a form called dati var nome_var="email"; //for exemple ex1=document.dati.elements.value //it's ok, work right document.dati.email.focus( ) //it's ok, work right document.dati.elements.focus( ) //it's ok, work right //but i need something like this:
2
1241
by: Kae Verens | last post by:
Anyone know of a script which returns a list of elements matching a specified CSS selector? Kae
3
1607
by: Christopher Benson-Manica | last post by:
I appreciate all the responses to my earlier post about accessing named elements. However, I'm still wondering about my actual problem, which is that I need to initialize some arrays of named elements when the document is loaded so they can be used by other functions used as event handlers. What I have now is that every function that requires these arrays checks to see whether they have been initialized, and if not initializes them. ...
2
6600
by: thomasamillergoogle | last post by:
Hi, As you can see from the code below I have a simple js function called getFormElementsinTableRow(rowName). rowName is the ID of the tableRow. I just want to use js to find the child ID's of all the form elements in that particular tableRow. What am I doing wrong? <table><tr id="where12" style="DISPLAY:none"> <td><select name="parameter12" id="parameter12"> <option value="1">casenumber</option> <option value="2">analyst</option>
5
2448
by: Dani | last post by:
Hello everybody, I have some code that disables form elements on body load, but I notice when I hit the "back" button, I need to re-enable the form elements (that is done by clicking on a radial button). Is there any way I can keep the form for disabling every time a user hits the back button and "remember" what elements should be enabled? I was thinking maybe utilizing some referrer thing, but I'm not that good with JS yet. Thanks...
5
1907
by: ojvm | last post by:
ok. thanks again for the time spend reading this. this code adds 2 controls in html form but it places in top of the form. i want this control1 control2 control1 control2 control1 control2
4
12772
by: Claudio Calboni | last post by:
Hello folks, I'm having some performance issues with the client-side part of my application. Basically, it renders a huge HTML table (about 20'000 cells in my testing scenario), without content. Content is "pushed" from the back via some JS, for the only displayed portion of table. Once the user scrolls, JS updates visible cells with data. It's quite the philosophy behind GMaps and similars. So, the server says to JS "update this group...
4
2144
by: Beagle804 | last post by:
OK. I'm very new to Javascript and what I've learned so far has been find snippets of code on the web and using them in my php programs. I put together an application that allows a Reset button to clear radio inputs in a portion of the page. And another button which will also set the values of these same radio's to a certain value. The form is for evaluating a speaker at a conference. I programmed everything using Firefox for testing and my...
0
9994
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9842
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11265
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...
0
9662
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8036
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
7191
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
6079
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4712
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
3
3309
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.