Solved

Adding click event

Posted on 2006-07-12
5
207 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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

When you need to keep track of a simple list of numbers or strings, the Array object is your most direct tool.  As we saw in my earlier EE Article (http://www.experts-exchange.com/A_3488.html), typical array handling might look like this: (CODE) B…
Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
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…

762 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now