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: -
addElementToPage("writeroot", "input", "type:button, text:testText, value:testvalue, onclick:test1")
-
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. -
AttachEvent("submitButton",'click',test1,false);
-
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: -
obj has no properties
-
if (obj.addEventListener){
-
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. -
-
<!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="Javascript">
-
-
var eventHandlers = new Array("onabort", "onblur", "onchange", "onclick", "ondblclick", "onerror", "onfocus", "onkeydown", "onkeypressnload", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onreset", "onresize", "onselect", "onsubmit", "onunload")
-
var month = new Array("January","February","March","April","May","June","July","August","September","October","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(document.getElementById("submitButton"),'click',test1,false);
-
addElementToPage("writeroot", "input", "id:testID, name:testName, type:button, text:testText, value:asdfg, onclick:test1, class:test123")
-
// newWin();
-
}
-
-
function AttachEvent(obj,evt,fnc,useCapture){
-
-
obj = document.getElementById(obj);
-
-
if (!useCapture) useCapture=false;
-
if (obj.addEventListener){
-
obj.addEventListener(evt,fnc,useCapture);
-
return true;
-
} else if (obj.attachEvent) return obj.attachEvent("on"+evt,fnc);
-
else{
-
MyAttachEvent(obj,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: addElementToPage("writeroot", "input", "type:button, text:testText, value:testvalue, onclick:test1")
-
function addElementToPage(locationID, elementType, elementArgs) {
-
elementArgs = removeSpaces(elementArgs);
-
var elementArgs = elementArgs.split(",");
-
var argsParsed = new Array();
-
var storedArguments = new Array();
-
-
//alert("elementArgs: " + elementArgs[0]);
-
//alert("argsParsed: " + argsParsed);
-
//alert("storedArguments: " + storedArguments);
-
-
// Finishes parsing the arguments and stores in a 2-dimensional array
-
for(i=0; i <= elementArgs.length-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.createElement('<' + elementType + ' name=\"' + elementName + '\">');
-
}
-
catch (e) { // For any other explorer
-
var element = document.createElement( elementType);
-
}
-
-
for(i=0; i <= elementArgs.length-1; i++) {
-
if (argsParsed[0] == "name" ) {
-
element.setAttribute( "name", elementName );
-
}
-
else if (argsParsed[0] == "multiple" || argsParsed[0] == "disabled") {
-
element.setAttribute( storedArguments[i][0], storedArguments[i][0]);
-
}
-
else {
-
element.setAttribute( storedArguments[i][0], storedArguments[i][1] );
-
}
-
}
-
-
// Adds element box to page
-
document.getElementById(locationID).appendChild( element );
-
-
// Adds any event handlers to the page
-
for(i=0; i <= storedArguments.length-1; i++) {
-
for(j=0; j <= eventHandlers.length-1; j++) {
-
if (storedArguments[i][0] == eventHandlers[j]) {
-
//alert("Element ID: " + elementID);
-
//alert("Element Name: " + elementName);
-
//alert("storedArguments[i]: " + storedArguments[i]);
-
//alert("eventHandlers[j]: " + eventHandlers[j]);
-
AttachEvent(elementID,'click',test1,false);
-
}
-
}
-
}
-
-
if( elementType == "select") {
-
addOption(elementName,month,month1)
-
}
-
}
-
-
function test1(){
-
alert("test");
-
}
-
-
function addOption(selectBoxID, optionNameArray, optionValueArray )
-
{
-
for (var i=0; i < optionNameArray.length-1;++i){
-
var optn = document.createElement("option");
-
optn.setAttribute( "text", optionNameArray[i] );
-
optn.setAttribute( "value", optionValueArray[i] );
-
document.getElementById(selectBoxID).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="submitButton"/>
-
</form>
-
</body>
-
</html>
-
-
5 2226 epots9 1,351
Recognized Expert Top Contributor
to add a onclick event try using: -
element.onclick = function(){//call method or do something};
-
good luck
to add a onclick event try using: -
element.onclick = function(){//call method or do something};
-
good luck
Well that works. However, I am not always going to use "onclick" and will not always call the same function. Can a variable be used in place of the onclick in element.onclick and can I use a variable that has a set function name string set to it within the brackets of function() { }?
Also, is using element.onclick cross browser? What is the difference in using setAttribute, attachEvent/addEventListene r, and your method?
epots9 1,351
Recognized Expert Top Contributor
the setAttribute works every well (the way it should) in firefox, but ie has some issues with it, so using element.attribu te (which is DOM) is cross-browser safe, works in firefox and ie won't complain (for once).
inside the function(){} baskets u can put a function call: -
element.onclick = function(){popup();};
-
//if u had a function called popup, it would be called when clicked.
-
the setAttribute works every well (the way it should) in firefox, but ie has some issues with it, so using element.attribu te (which is DOM) is cross-browser safe, works in firefox and ie won't complain (for once).
inside the function(){} baskets u can put a function call: -
element.onclick = function(){popup();};
-
//if u had a function called popup, it would be called when clicked.
-
Below is essentially what I would like to do (although it currently doesn't work). I want to be able to dynamically set the function that is called as well as the type of event it sets. -
var functionVar = "test1();"
-
var eventVar = "onmousedown"
-
element.eventVar = function(){functionVar}
-
Since this doesn't work, is there another way to do this?
Well this is the solution I came up with. -
var t = "element." + storedArguments[i][0] + " = function(){" + storedArguments[i][1] + "};"
-
eval(t);
-
It works both in IE and Firefox. Now, I seem to remember reading somewhere that eval is not good to use. If that is the case then why should it not be used and is there any alternative to what I'm doing here?
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: flupke |
last post by:
Hi,
i create my GUIs mainly via wxGlade. However when you start of to
program and want to do some rearranging to the gui, wxglade overwrites
your file and you've got to put your own code back in.
I think i can work around that (at least a bit) by making a second file
that imports the gui generated by wxglade and make classes that extend
the original ones.
For instance i could have a class MainForm that extends the wxFrame
|
by: Jason Madison |
last post by:
We sometimes get very large databases that we want to cut down to use for
testing.
The information is all related to a central accounts table.
The way I thought of doing this is to grab all the foreign constraints and
turn them into cascade delete constraints, then delete as many accounts as I
want.
After this I will restore the constraints back to their original state.
|
by: Poul Møller Hansen |
last post by:
I have made a stored procedure, containing this part for generating a unique
reference number.
SET i = 0;
REPEAT
SET i = i + 1;
SELECT RAND()
INTO reference
FROM SYSIBM.SYSDUMMY1;
SET p_reference = ref_prefix || SUBSTR(CAST(reference AS CHAR(12)),3);
|
by: Lars Netzel |
last post by:
Hey!
I wrote a message yersterday and got some good answers and have now managed
to generate a nice image. The problem is that it's all generated in an
Images.Aspx file and I don't really want that. I am writing a WebControl
Library and I want to generate everything from there...
In the Render Sub of the Control I output some HTML and there I need to
reference to a file in the <img> element, is there anyway to NOT have to
point to a...
|
by: daniele.balducci |
last post by:
Hi All,
I'm generating XLS files from ASP(.Net) code using the usual code
chunks ...
Response.ContentType = "application/vnd.ms-excel"
Response.AppendHeader("Content-Disposition", "attachment; filename=""" &
NomeFile & """")
Response.Flush()
Response.write("<table border=""1"" .....
| |
by: R.A.M. |
last post by:
Hello,
I am learning .NET 2.0. I need to learn how to create documentation
from /// comments. I downloaded sample project XMLsample from Web and
I generated XML documentation XMLsample.xml:
<?xml version="1.0"?>
<doc>
<assembly>
<name>XMLdoc</name>
</assembly>
|
by: Alex Maghen |
last post by:
I want to create an ASP.NET class which generates some client-side HTML
objects on a page with the following rules:
1. Only generate these objects from the class if they haven't already been
inserted by another instantiation of this class. So if the obejcts have
already been inserted, determine that this is the case and don't do it again.
2. Insert these HTML objects at the very end of the <BODYof the page,
preferably without the...
|
by: Cesar |
last post by:
Hello there,
A java programmer sent me a wsdl file, which I have to use to consume his
web methods. When I run the wsld.exe tool to generate the class' code, I get
the following message:
CODEGEN: The operation binding 'getAvaluos' from namespace
'urn:m15.AvaluosPortType' was ignored. The combination of style=rpc with
use=literal is not supported.
|
by: bilgekhan |
last post by:
What is the correct method for generating 2 independent random numbers?
They will be compared whether they are equal.
What about this method:
srand(time(0));
int r1 = rand();
srand(rand());
int r2 = rand();
bool f = r1 == r2;
|
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...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
| |
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...
|
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();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |