Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Set OnClick attribute with value containing function in ie8?

My goal is to change the onclick attribute of a link. I can do it successfully, but the resulting link doesn't work in ie8. It does work in ff3.

For example, this works in Firefox 3, but not IE8. Why?

<p><a id="bar" href="#" onclick="temp()">click me</a></p>  <script>     doIt = function() {         alert('hello world!');     }     foo = document.getElementById("bar");     foo.setAttribute("onclick","javascript:doIt();"); </script> 
like image 777
edt Avatar asked Jun 19 '09 17:06

edt


People also ask

How do you write a function on onclick event?

Just invoke the code you're trying to invoke: onclick="alert('hello')" If you want to define a function, do that separately in your JavaScript code and just invoke the function in onclick . (Or, even better, attach it as a handler from the JavaScript code so you're not writing in-line JavaScript in your HTML.)

How do you call a function onclick?

window. onload = function() { document. getElementById("Save"). onclick = function fun() { alert("hello"); f1(); //validation code to see State field is mandatory. } }

Which method we used to create onclick function on button?

When the user clicks a button, the Button object receives an on-click event. To define the click event handler for a button, add the android:onClick attribute to the <Button> element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event.


1 Answers

You don't need to use setAttribute for that - This code works (IE8 also)

<div id="something" >Hello</div> <script type="text/javascript" >     (function() {         document.getElementById("something").onclick = function() {              alert('hello');          };     })(); </script> 
like image 104
hugoware Avatar answered Oct 02 '22 08:10

hugoware