Solved

Adding click event

Posted on 2006-07-12
5
215 Views
Last Modified: 2006-11-18
I am trying to add a click event to a button that is created dynamically. I want the click event to trigger a function that takes a parameter.

The function I am trying to trigger could be as simple as :
  function MyAlert(name)
  {
      alert("hello " + name);
  }

and my dynamic button like:

   var MyButton = document.createElement("INPUT");
   MyButton.value = "Click Me";
   MyButton.type = "Button";
   
In non-IE browsers I can use the setAttribute method like this:
  MyButton.setAttribute("onclick", "MyAlert('John');");

but in IE I have to use the attachEvent method like this
  MyButton.attachEvent("onclick", MyAlert);

My problem is HOW CAN I PASS THE NECESSARY PARAMETERS TO THE FUNCTION since the MyAlert function take the "name" parameter?

All help appreciated
0
Comment
Question by:dav_evans
5 Comments
 
LVL 30

Assisted Solution

by:third
third earned 250 total points
ID: 17096968
try,

<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Third Santor</title>
<script>
  function MyAlert(name)
  {
      alert("hello " + name);
  }

  function newElement(){
    var MyButton = document.createElement("INPUT");
    MyButton.value = "Click Me";
    MyButton.type = "Button";

      MyButton.setAttribute("onclick", "MyAlert('John')");

      if ((!document.all)&&(document.getElementById)){
       MyButton.setAttribute("onClick", "MyAlert('John')");
   }    
   //workaround for IE 5.x
   if ((document.all)&&(document.getElementById)){
       MyButton["onclick"]=new Function("MyAlert('John')");
   }
   document.form1.appendChild(MyButton);
  }
</script>
</head>
<body topmargin="0" leftmargin="0" marginwidth="0" marginheight="0">
<form name="form1" method=post action="">
<input type="button" value="Create New Element" onclick="newElement();">
</form>
</body>
</html>
0
 
LVL 30

Expert Comment

by:third
ID: 17096973
opps, please remove the extra

MyButton.setAttribute("onclick", "MyAlert('John')");

outside the if condition.
0
 
LVL 8

Assisted Solution

by:kaliyugkaarjun
kaliyugkaarjun earned 125 total points
ID: 17097223

There is 1 example to pass parameters in aatachEvent ...chk if u get any idead through it

http://www.sitepoint.com/forums/showthread.php?t=168890&goto=nextoldest
0
 
LVL 17

Accepted Solution

by:
gops1 earned 125 total points
ID: 17099899
I guess you do not have to use attachevent. Instead of setAttribute use this:

 MyButton.onclick=function(){MyAlert('John');}  

Here is a sample code with complete implementation:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<html>
<head>
      <title>Untitled</title>
      <script language="javascript">
            function MyAlert(params){
                  alert(params);
            }
      </script>
</head>

<body>

<p> Form 1<br></p>
<form name="firstForm">

</form>

</body>
</html>
<script language="javascript">
    var MyButton = document.createElement("INPUT");
    MyButton.value = "Click Me";
    MyButton.type = "Button";
    MyButton.onclick=function(){MyAlert('John');}
    document.forms[0].appendChild(MyButton);

</script>
0
 

Author Comment

by:dav_evans
ID: 17104428
Hi All,
  I think I may have worked out the best solution for my situation.

  I dont want to have to write the body of a function inside the onclick declaration because I dont want to have to repeat the myAlert code in each declaration
  eg:
  MyButton.onclick=function(){MyAlert('John');}

  What I've found is that event arguments are implicitly passed to functions when they are triggered as events, and you can use the event arguments to get the properties of the source element as parameters of sorts.
  So Ive added property to my button like so:
  MyButton.FavoriteColor = "Blue";

  and then in the myAlert function rather than taking a paramater like "name", specify a paramater that is the event (I've used "e")
  function MyAlert(e)
 {
    alert("the button you clicked came from button with favorite color: " + e.srcElement.FavoriteColor);
 }

  I also found a good function elsewhere on the web for doing the attaching of the onclick event so that is cross-broswer compatible.
  function addEvent( obj, type, fn ) {
    if ( obj.attachEvent ) {
         obj['e'+type+fn] = fn;
         obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
         obj.attachEvent( 'on'+type, obj[type+fn] );
    } else
        obj.addEventListener( type, fn, false );
  }


   sp putting all these together I am able to retrieve a custom property of my button inside the click event and use these as psuedo parameters.

   I hope this helps

   
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Today I would like to talk about localizing (Internationalization) JavaScript applications. Introduction When creating an application that is going to be used by many people around the globe, it is important to remember that not everyone speak…
Article by: DanRollins
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7850-Hex-Maze-Part-2.html), we'll extend the program by adding a depth-…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

680 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question