473,799 Members | 3,161 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

create element and set onclick function

Hi, here is my code:
<html>
<head>
<script type="text/javascript">

function setImage(num)
{
alert(num);
}

function init()
{
for (var i = 0; i < 5; i++){
var button = document.create Element("input" );
button.type = "button";
button.value = "Image ";
button.onclick = setImage(button );
document.body.a ppendChild(butt on);
}
}
</script>
</head>
<body onload="init(); ">
</body>
</html>

why it is wrong? How to fix it?

Thanks,

qq

Jul 16 '06 #1
1 3832
qu******@yahoo. com wrote:
Hi, here is my code:
<html>
<head>
<script type="text/javascript">

function setImage(num)
You seem to expect to pass a value to the function, but your code below
doesn't do that. I'll guess that you are trying to pass 'i' from init's
for loop.

{
alert(num);
}

function init()
{
for (var i = 0; i < 5; i++){
var button = document.create Element("input" );
button.type = "button";
button.value = "Image ";
button.onclick = setImage(button );
That will assign the result of setImage(button ) to the value of the
button's onclick attribute. What you need to do is assign a reference
to the function itself:

button.onclick = setImage;

But you want to pass a value, so the next thing that you might try is:

button.onclick = function(){ setImage(i); }
Which 'works', but it creates a closure back to the init's local i. All
the buttons will alert '5', which is the value of i when the function
finished, not its value when each onclick handler was set.

There are a couple of ways to break the closure, one is to use the
Function object as a constructor, but that is not liked as it is
considered only marginally better than using eval. You can either
create a separate function to add the onclick:

function addOnclick(obj, func, val){
obj.onclick = function(){func (val)};
}

and call it like:

addOnclick(inpu t, setImage, i);
or you can use a function expression:

input.onclick = (function(i){
return function(){ setImage(i);}
})(i);
which is somewhat more convoluted, but probably neater overall.

[...]

--
Rob
Jul 16 '06 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
5380
by: js | last post by:
Two questions: 1. I created Javascript objects called oNewObj using {} construct as in the follwoing code segment. When I clicked on the <td> element, I got runtime error "oNewObj is undefined". When I changed the <td> onclick event to doThis(this), then I can exam (this) object. However, I really want to exam the oNewObj. Does anyone know how to do it? Thanks. 2. I need to add additional things to the oNewObj, how could I append
4
45001
by: Michael Hill | last post by:
I had this html: <tr id="action" title="click to do something" onclick="alert('mike');"> <td>a</td> <td>b</td> </tr> and it works when I click on the row, but when I try to add it dynamically like:
2
18581
by: RobG | last post by:
I am trying to dynamically add an onclick to an element, however I just can't get the syntax right. consider the following function: function doClick (evt,x) { // do things with evt and x } Which is called statically by: <button onclick="doClick(event,this);">Click me</button>
3
9146
by: takarimasu | last post by:
How can i create an input object (text area,select) at runtime ? B.
10
23293
by: Noozer | last post by:
Is it possible to detect where on a page the click occurred when the OnClick event of the BODY tag is fired? Thx
1
2074
by: shadow.demon | last post by:
G'day guys, i've looked around but i can't find how to create an A tag with a onclick to remove a row in a table. Can add rows to table, but i can't get it to create a link in the last coloumn to click to remove the row. I've got: var td6 = document.createElement("TD"); //create the TD var link = document.createElement("a") //create element a
3
5265
by: Beamer | last post by:
Hi I am trying to build a roating slide effect in javascript. Basically, I have a list like below <ul id="slideShowCnt"> <li id="slide0"><img .../></li> <li id="slide0"><img .../></li> <li id="slide0"><img .../></li> <li id="slide0"><img .../></li> <li id="slide0"><img .../></li> <li id="slide0"><img .../></li>
14
5198
RMWChaos
by: RMWChaos | last post by:
Firebug is reporting "too much recursion" when I attempt to create a child element in a parent that doesn't exist yet. The script should automatically create the missing parent before going on to create the child element. At the point where the script is supposed to call itself with the new properties to create the parent, it gives me the error and looks like it's looping the function continuously. It seems that "id : attrib" (line 192) is...
0
9541
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
10484
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
10251
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9072
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
7565
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
5463
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...
1
4141
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
2
3759
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2938
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.