[x]
Posted via EE Mobile

Search, ask, and monitor your questions on the go with EE Mobile. Visit Experts Exchange from your mobile device and never be out of touch again.

Question
[x]
Attachment Details
[x]
The Solution Rating System

With so many solutions, how can you tell which solutions are most likely to help you and which ones are not? To provide you with a tool to use, we rate our solutions based on various elements that most accurately determine if a solution is a quality solution. To explain what factors affect the solution rating, here are the elements we take into consideration when formulating our solution rating.

  • The Grade of the Solution
  • The Zone Rank of the Expert Providing the Solution
  • The Number of Author and Expert Comments
  • The Number of Experts Contributing
  • The Feedback of the Community

Your Input Matters
Because of the way the system is set up, the most important variable in this equation is you. As a member of Experts Exchange, you are able to cast your vote on the quality of the solutions in regard to how complete, accurate, helpful and easy to understand each solution is. When you provide your feedback, each rating is adjusted accordingly. So, if you see a solution that has a poor rating that you think is a good solution, let us know by rating it. As you do, the rating will be adjusted and will become more accurate for other members of our site.

If you have any suggestions that you would like to make for our rating system, please ask a question in the Suggestions Zone of Community Support.

Thank you!

7.4

Problem writing Javascript to the DOM in IE only

Asked by MatthewP in Document Object Model, Internet Explorer Web Browser, JavaScript

Tags: Javascript DOM XHTML Internet Explorer

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

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:
<!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>
 
Related Solutions
Keywords: Problem writing Javascript to the DOM i…
 
Loading Advertisement...
 
[+][-]04/08/09 10:46 AM, ID: 24099909Expert Comment

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]04/08/09 10:47 AM, ID: 24099916Expert Comment

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]04/08/09 11:09 AM, ID: 24100111Author Comment

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]04/08/09 11:19 AM, ID: 24100212Expert Comment

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]04/08/09 11:25 AM, ID: 24100282Author Comment

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]07/23/09 09:04 AM, ID: 24926770Author Comment

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]07/23/09 09:29 AM, ID: 24927095Expert Comment

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]10/16/09 06:56 AM, ID: 25589563Administrative Comment

Experts Exchange has a courteous staff of administrators who help members get the most out of the website by means of administrative comments like this one.

Start your 30-day free trial to view this Administrative Comment or ask the Experts your question.

 
[+][-]10/21/09 01:18 AM, ID: 25621634Accepted Solution

View this solution now by starting your 30-day free trial. Setting up your free trial is quick, easy, and secure. We will return you to this solution, unlocked, when you're done.

About this solution

Zones: Document Object Model, Internet Explorer Web Browser, JavaScript
Tags: Javascript DOM XHTML Internet Explorer
Sign Up Now!
Solution Provided By: ee_auto
Participating Experts: 2
Solution Grade: A
 
 
Loading Advertisement...
20091111-EE-VQP-89 - Hierarchy / EE_QW_3_20080625