...

View Full Version : Why is this code not working? (basic example)



joliett89
10-05-2011, 06:08 PM
<html>
<head>
<title>Click the button</title>
<script type="text/javascript">

function x() {
window.alert('1');
window.alert('2');
window.alert('3');
}

document.getElementById("y").onclick = x;

</script>
</head>
<body>
<form>
<input type="button" value="Click the button" id="y" />
</form>
</body>
</html>


By the way... Are there any good websites / validators that can be helpful in situations like that? I've been looking at this one so far:

http://www.jslint.com/

Thanks.

rangana
10-05-2011, 06:12 PM
window.onload = function() {
document.getElementById("y").onclick = x;
}

joliett89
10-05-2011, 06:17 PM
I need to do the following things though:

1) Write a function named x that will send three alerts to the viewer
2) Create a button in HTML document with an id name of y
3) Write a code in JS so the x function will execute when a user clicks on the button

Something like that doesnt work either:



var varName=document.getElementById("y");
varName.onclick=x;


Thats in place of:



document.getElementById("y").onclick = x;

rangana
10-05-2011, 06:30 PM
well, if you're not taking the first suggestion which obviously was working, then try:


<html>
<head>
<title>Click the button</title>
</head>
<body>
<form>
<input type="button" value="Click the button" id="y" />
</form>
<script type="text/javascript">

function x() {
window.alert('1');
window.alert('2');
window.alert('3');
}

//document.getElementById("y").onclick = x;
var varName=document.getElementById("y");
varName.onclick=x;
</script>
</body>
</html>

joliett89
10-05-2011, 06:35 PM
Thanks, I did not realize that placing the code under the input form makes a difference here.

rangana
10-05-2011, 06:42 PM
Placing the script under window.onload function is vital so that the script will trigger once the page has fully reload.

...but since you're not taking that suggestion, placing the script after the element has loaded can do the job too.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum