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:
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]
[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){
[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]
Comment