Question

Hi...

This is a Basic one but can't see were the error is. I just want that the button is recognized by the onclick and executes the function.

The HTML file is like this


<html>
<head>
<script type="text/javascript" src="His.js"></script>
</head>

<body>
<form>
<input type="button" value="Click Me!" id="btnClickMe">
</input>
</form>
</body>
</html>
[/CODE]

The js file is like this

[CODE]

//window.alert('Testing');
var varBtnClickMe = document.getElementById("btnClickMe");
varBtnClickMe.onclick = functHis();

function functHis(){
window.alert('Hi there!');
window.alert('It\'s me again!');
}
[/CODE]

Thank you

Link to comment
https://www.neowin.net/forum/topic/1057480-basic-onclick/
Share on other sites

4 answers to this question

Recommended Posts

  • 0

If you really want to set the click event programatically and not as Protagonist says, then you will need to amend your script and HTML slightly; your current code isn't working because by default, scripts in the head of an html doc are executed immediately; if you debug that script you'll find that your variable "varBtnClickMe" is null because when the script runs, the DOM isn't ready yet, and the button doesn't actually exist!

We can get round this by only setting everything up once the DOM is ready:


<html>
<head>
<script type="text/javascript" src="his.js"></script>
</head>
<body>
<form>
<input type="button" value="Click Me!" id="btnClickMe">
</input>
</form>
</body>
</html>
[/CODE]

Then the JS:

[CODE]
function functHis() {
window.alert('Hi there!');
window.alert('It\'s me again!');
}
window.onload = function() {
var varBtnClickMe = document.getElementById("btnClickMe");
varBtnClickMe.setAttribute('onclick', 'functHis()');
}
[/CODE]

  • Like 1
Link to comment
https://www.neowin.net/forum/topic/1057480-basic-onclick/#findComment-594647726
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.