all! I am having a problem using the a simple onclick method. Kindly please help me out. Here is that code... When i click on the button nothing really happens.
Try this: http://jsfiddle.net/uxfD4/
the onclick assignment accepts a function. What your code did was evaluate alert('hi'), returning null.
window.onload=initall();
calls the function initall
and assigns the return value of initall
as event handler. That is, initall
is executed immediately and not when the load
event is triggered.
Similar for btn.onclick=alert('hi');
. But in both cases, the return value is not a function.
You have to assign functions to those properties, which are then being called when the event occurs.
function initall(){
var btn = document.getElementById('btn');
btn.onclick = function() { // creates and assigns the function at once
alert('hi');
};
}
window.onload = initall; // assign the function reference, no `()`.
I recommend to read the excellent tutorials at quirksmode.org to learn about event handling and of course the MDN JavaScript Guide for the JavaScript basics.
Onclick should be a function, not a statement. Try
btn.onclick=function(){
alert('hi');
}
Try this for onclick javascript function call
function initall(){
var btn=document.getElementById('btn');
btn.onclick=alert('hi');
}
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="testjs.js"></script>
</head>
<body>
<input type="text" required name="id">
<input type="button" id="btn" value="send" onclick="javascript:initall();">
<div id="result"></div>
</body>
</html>