Jump to content

Problem with Function inside getElementById().onclick


fai960820

Recommended Posts

Here is the problem...

<button onclick="show()">HelloWorld</button><script type="text/javascript">function show(){document.write("<button id=\"a\">Press Me</button>");document.getElementById("a").onclick = function{alert("two");}}

The "HelloWorld" button will work, it will overwrite (i want it overwrite) and show the "Press me" button. The problem is in the "Press me" button, it wont alert "two", there is no respown. If i change it like this...

<button onclick="show()">HelloWorld</button><script type="text/javascript">function show(){document.write("<button id=\"a\">Press Me</button>");document.getElementById("a").onclick = alert_two();}function alert_two(){alert("two");}

It would alert two when "Hello World" button is press, but not "Press Me" button. Where is my problem?? Please Help~

Link to comment
Share on other sites

Try putting the functions in the head of the document like the following and remove the parenthesis from alert_two() for onclick. What it's doing is, when it reaches that it executes. By removing it, you instead have it set where it will wait til the button is clicked on and then it will run the alert_two() function.

<!DOCTYPE HTML><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title></title><script type="text/javascript">function show(){     document.write('<button id="a">Press Me</button>');     document.getElementById("a").onclick = alert_two;} function alert_two(){     alert("two");}</script></head> <body><button onclick="show()">HelloWorld</button> </body></html>

Link to comment
Share on other sites

I know what is the problem! It only doesnt work in IE, others work.' (Only IE have problem) Is there a way to slove that? also, if i want alert_two to have arguments, like

function show(){	 document.write('<button id="a">Press Me</button>');	 document.getElementById("a").onclick = alert_two("HelloWorld");} function alert_two(x){	 alert(x);}

It will alert when i press "Hello World" which i dont want , is there an way to slove that? (Not only IE) btw, really thank you for you help. :D

Link to comment
Share on other sites

Change:

document.getElementById("a").onclick = alert_two("HelloWorld");

To:

document.getElementById("a").onclick = function () {alert_two("hello world");};

That should solve the problem when clicking on the hello world button. It won't alert "hello world" but instead only when clicking on 'Press Me' button as intended. Works in Chrome and FireFox.

Edited by Don E
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...