Question

Problem writing Javascript to the DOM in IE only

Asked by: MatthewP

I've got a bit of a confusing one here regarding writing to the DOM on the fly. I've included a stripped down version of my page in the code section below to highlight the problem that can be reproduced locally.

If you run the page in Firefox and the IE7 it should be pretty obvious what the problem is, but I'll explain: I start my page with 2 select fields in static HTML - the options/values of the second are written dynamically depending on what is selected in the first select field, so they work as a pair. The first is a category, the second essentially is a product. This bit is working fine, when i change category the options change in the product drop down.

I now have a button to add further pairs of these select fields to create further category/product inputs, and when this button is clicked there's a fair amount of script which creates notes and inserts them into the DOM in the appropriate place, giving new names to the fields based on a random number. This bit actually works fine too, and even a button to remove the parent paragraph tag which the new select pairs are in works fine in both browsers.

What Im having trouble with is setting the attribute of 'onChange' in the first select to call the javascript function. The function requires two parameters - the selectedIndex and the name of the field to update, and this is done in line 73 - the variable "passFunctionInSetAttr" is set and ontains the complete function call. This is then added to the node 3 lines later (after being alerted to the screen so I can see what is going on and that it is fine - it is).

And in firefox it works perfectly - I get an alert to say that its reached the updateproducts  function as expected and the newly created select list updates with the products list, but in IE (Im in version 7) - despite that I'm echoing the string back in the alert to see it's working - and it seems to be - it fails silently without an error message or anything and it doesnt reach the function to update the products - I can tell as the alert doesnt come up. I've been pulling this apart today in Visual Web Developer 2008 to try and get some debugging messages and theres no error message or anything, yet it doesn't work and fails in total silence.

I've added a 'Print Dom' button to this too, so I can print out the structure of the document that's been written on the fly and take a look - and it does look a little odd - the paragraph id isn't quoted for example (how can I change this I wonder..) but it seems to look vaguely ok.

Weirdly though, if i then paste the dom that is dumped out into the text area into its own document, and run it locally in a browser (just need to add the Doctype and HTML tags around the core code), it then gets as far as the function in IE and flashes up the alert which it didn't before. It still fails to update the second select..  but this is supposed to be exactly the same script, just one is written on the fly and the other has been run from a static HTML document - and its behaving differently.

Not sure if I've done something stupid here or hit a Javascript bug, but many thanks in advance for any help anyone can give me on this!

Matt

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Select DOM Test</title>
<script type="text/javascript">
    function node_delete(whichPara) {
        if (confirm("Are you sure you want to delete this product?")) {
            document.getElementById('allparas').removeChild(document.getElementById(whichPara));
       }
    }
 
    function printDom() {
        allHTML = document.getElementsByTagName("html")[0].innerHTML;
        document.forms['update_table'].elements['dom'].value = allHTML;
 
    }
    var products_matrix = new Array();
    products_matrix[0] = "";
    products_matrix[1] = new Array("550|X1|product 1|10");
    products_matrix[2] = new Array("551|Y1|Product in section 2|10", "552|Y2|Another Product in Section 2|10");
    products_matrix[3] = new Array("640|B-682|Product in 3|1", "641|B-682-int|Another in 3|1", "642|CD-682|Product|1", "643|CD-6821|Another Product|1", "644|CD-C|And Another Product|1");
    products_matrix[4] = new Array("611|E-API682sd|Item in section 4|15", "612|B-AP|Another item in section 4|15", "613|S2wed|item name here|20", "614|B-Chem|Another items|15", "615|B-Chem|and another|15", "616|B-C|Aargh|15", "624|B-Oi|Final test product|15");
 
    var categories_names_array = new Array("Section 1", "Section 2", "Section 3", "Section 4");
    var categories_ids_array = new Array("6", "7", "12", "9");
 
    function updateproducts(selectedcategory, fieldtoupdate) {
        alert("reached update products function");
        
        var categorieslist = document.update_table.category1
        var productslist = eval("document.forms['update_table'].elements['" + fieldtoupdate + "']")
 
        productslist.options.length = 0
        if (selectedcategory > 0) {
            for (i = 0; i < products_matrix[selectedcategory].length; i++)
                productslist.options[productslist.options.length] = new Option(products_matrix[selectedcategory][i].split("|")[1] + "  -  " + products_matrix[selectedcategory][i].split("|")[2], products_matrix[selectedcategory][i].split("|")[0]);
        }
    }
 
    //-->
</script>
</head>
<body>
 
<form name="update_table" method="post" action="" enctype="multipart/form-data" style="padding:0px; margin:0px">
<p style="font-size:12px">Select Category:<br />
<select name="category1" onChange="updateproducts(this.selectedIndex,'product1')" />
<option value="">Select a category:</option>
<script language="Javascript">
    for (p=0;p<categories_names_array.length;p++){
	document.write("<option value=\"" + categories_ids_array[p] + "\">" + categories_names_array[p] + "</option>\n");
    }
</script></select>
</p>
 
<p style="font-size:12px">Product Name: <select name="product1" style="font-size:13px">
<option value="" style="font-family:tahoma,arial,verdana,helvetica"> Please select a category first </option>
</select>
</p>
 
<div id="allparas">
<span class="order_button" style="margin-top:30px"><a style="font-weight:bold; clear:both; padding-top:10px; margin-top:10px;" href="#" onclick="
if( !document.createElement || !document.childNodes ) {
	window.alert('Your browser is not DOM compliant');
} else {
	// set up paragraph and select
	randomNumber = Math.floor(Math.random()*9999999999999999) 
	var theNewParagraph = document.createElement('p');
	var lineBreak = document.createElement('br');
	var divName = 'div_' + randomNumber;
	var theTopCategorySelect = document.createElement('select');
	var theSelect = document.createElement('select');
	newSelectName= 'select_' + document.getElementsByTagName('p').length;
	newCatSelectName= 'select_category_' + randomNumber
    myRandomNumber = Math.floor(Math.random()*9999999999999999);
	newSelectName = newSelectName + myRandomNumber;
    theSelect.setAttribute('name',newSelectName);
    theSelect.setAttribute('style','font-size:13px;');
	theTopCategorySelect.setAttribute('name',newCatSelectName);
	theTopCategorySelect.setAttribute('style','font-size:13px');
    
	passFunctionInSetAttr='updateproducts(this.selectedIndex,\'' + newSelectName + '\')';
	alert(passFunctionInSetAttr);
	
	theTopCategorySelect.setAttribute('onChange',passFunctionInSetAttr);
 
	// set up options for select
	firstOption = document.createElement('option');
	firstOption.setAttribute('value','');
	firstOption.setAttribute('style','font-weight:bold; font-size:12px');
	firstText = document.createTextNode(' - ');
	theSelect.appendChild(firstOption);
	firstOption.appendChild(firstText);
	arrayOptions=Array();
	arrayText=Array();
   
	// set up options for category select
	catFirstOption = document.createElement('option');
	catFirstOption,setAttribute('value','');
	catFirstOption.setAttribute('style','font-weight:bold; font-size:12px');
	catFirstText = document.createTextNode('Select A Category:');
	theTopCategorySelect.appendChild(catFirstOption);
	catFirstOption.appendChild(catFirstText);
	arrayOptions=Array();
	arrayText=Array();
    for (p=0;p<categories_ids_array.length;p++){
		arrayOptions[p] = document.createElement('option');
		arrayOptions[p].setAttribute('value',categories_ids_array[p]);
		arrayOptions[p].setAttribute('style','font-size:13px; ');
		arrayText[p] = document.createTextNode(categories_names_array[p]);
		theTopCategorySelect.appendChild(arrayOptions[p]);
		arrayOptions[p].appendChild(arrayText[p]);
	}
 
	var theDeleteImage = document.createElement('img');
	
	//set up theNewParagraph
	newParaName= 'para_' + document.getElementsByTagName('p').length;
	newParaName += randomNumber; 
	theNewParagraph.setAttribute('id',newParaName);
	theNewParagraph.setAttribute('style','padding-top:10px; font-size:12px; clear:both;');
 
    // delete image 
	theDeleteImage.setAttribute('src','http://www.dmlmarketing.net/demo/cancel.png');
	deleteImageName = 'delete_' + document.getElementsByTagName('p').length;
	deleteImageName += randomNumber; 
	theDeleteImage.setAttribute('id',deleteImageName);
	theDeleteImage.setAttribute('hspace','20');
	theDeleteImage.setAttribute('vspace','3');
 
    // div
	theDiv = document.createElement('div');
	theDiv.setAttribute('id',divName); 
	theDiv.setAttribute('style','display:inline; float:left;'); 
 
 	//prepare the text nodes
	var theText1 = document.createTextNode('Product Name:');
    theCategoryText = document.createTextNode('Select Category:');
       
    
	//put together the whole paragraph
	theNewParagraph.appendChild(theCategoryText);
	theNewParagraph.appendChild(lineBreak);
	theNewParagraph.appendChild(theTopCategorySelect);
	theNewParagraph.appendChild(lineBreak);
	theNewParagraph.appendChild(theText1);
	theNewParagraph.appendChild(theSelect);
	theNewParagraph.appendChild(theDiv);
	theDiv.appendChild(theDeleteImage);
	
	//insert it into the document somewhere
	this.parentNode.parentNode.insertBefore(theNewParagraph,this.parentNode);
	//make the paragraph delete itself when the delete image is clicked
	document.getElementById(deleteImageName).onclick = function () { node_delete(this.parentNode.parentNode.id); };
}
return false;">Add New</a></span>
<hr />
<span style="disaply:block; clear:both;"><textarea name="dom" rows=10 cols=70></textarea><br /><a href="Javascript:printDom()">Print Dom</a></span>
</form>
</body>
</html>

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-04-08 at 10:04:59ID24306591
Tags

Javascript DOM XHTML Internet Explorer

Topics

Document Object Model

,

Internet Explorer Web Browser

,

JavaScript

Participating Experts
2
Points
0
Comments
9

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Javascript and Firefox DocType question
    Hi, I've been looking at the Javascript here http://javascript.internet.com/miscellaneous/image-viewer.html for a simple image viewer. SCRIPT LANGUAGE="JavaScript"> <!-- This script and many more are available free online at --> <!-- The JavaScript ...
  2. Firefox, XML, and the DOM
    I'm trying to load an XML document IN FIREFOX into the DOM and output it through the innerHTML command. In IE it is trivial, but I can't get it to work with Firefox. There are two approaches below, one is commented out. Any suggestions? xmlDoc= document.imple...
  3. DOM alternative to innerHTML
    I am trying to get the contents of an iFrame and put them in a hidden field in my form using Javascript. I have tried using the innerHTML method, but this falls over in IE (perfect in firefox). So I am now trying a different method, which I found somewhere on the internet w...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: HonorGodPosted on 2009-04-08 at 10:46:16ID: 24099909

I'm pretty sure that the problem is with this line of code:

document.getElementById(deleteImageName).onclick = function () { node_delete(this.parentNode.parentNode.id);

I've had problems before trying to change the onclick in IE.
What I had to end up doing was checking for an attachEvent function associated with the object (element), and using it, instead of the
assignment like you have, or setAttribute.

Something like:

var ele = document.getElementById( 'deleteImageName' )
if ( ele.attachEvent ) {
  ele.attachEvent( 'onfocus', function() { doSomething(this.event.srcElement); } )
} else {
  ele.setAttribute( 'onclick', 'doSomething(this);' );
}

                                              
1:
2:
3:
4:
5:
6:

Select allOpen in new window

 

by: HonorGodPosted on 2009-04-08 at 10:47:19ID: 24099916

sorry, the attachEvent should have been

ele.attachEvent( 'onclick', function() { doSomething(this.event.srcElement); } )

                                              
1:

Select allOpen in new window

 

by: MatthewPPosted on 2009-04-08 at 11:09:24ID: 24100111

Hi,

Thanks for taking a look. did you try running the code locally? The delete is working perfectly for me in both browsers, its the onChange when written to the DOM that is failing.

Thanks,
Matt

 

by: HonorGodPosted on 2009-04-08 at 11:19:36ID: 24100212

Haven't had a chance yet... Trying to do way too many things at once. :-)

 

by: MatthewPPosted on 2009-04-08 at 11:25:49ID: 24100282

Tell me about it :) I've been on this 2 days and not got anywhere, I need to forget about it for a bit. If you're up for taking a look though the script i sent should demonstrate it pretty succinctly. I've either done something very stupid.. or its an IE bug.. i *think*.

Cheers,
matt

 

by: MatthewPPosted on 2009-07-23 at 09:04:05ID: 24926770

Bit of a curious one this, I got it fixed but not by what I was trying to do but by adding another line similar to:

document.getElementById(deleteImageName).onclick = function () { node_delete(this.parentNode.parentNode.id); };

it all worked correctly - it seems that the event wouldnt attach directly to the element but would if I attached it later. Not figured out why but there you go.

 

by: HonorGodPosted on 2009-07-23 at 09:29:23ID: 24927095

Wow, somehow, I lost track of this, and never returned.

Please forgive me.

I'm glad that you were able to get the issue resolved though.

 

by: ee_autoPosted on 2009-10-21 at 01:18:06ID: 25621634

Question PAQ'd, 500 points refunded, and stored in the solution database.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...