Javascript append to onClick event
Posted
by John Hartsock
on Stack Overflow
See other posts from Stack Overflow
or by John Hartsock
Published on 2010-05-07T17:53:32Z
Indexed on
2010/05/07
17:58 UTC
Read the original article
Hit count: 164
JavaScript
|html
Guys I have the following Code which I know doesnt work correctly. Yes I know how to do this in JQuery but In this case I cannot use jquery. Please no jquery answers.
<form>
<input type="text" name="input1" onclick="alert('hello')">
<input type="text" name="input2">
<input type="text" name="input3">
</form>
<script type="text\javascript">
window.onload = function () {
var currentOnClick;
for (var i = 0; i < document.forms[0].elements.length; i++) {
currentOnClick = document.forms[0].elements[i].onclick;
document.forms[0].elements[i].onclick = function () {
if (currentOnClick) {
currentOnClick();
}
alert("hello2");
}
}
}
</script>
What Im trying to do is iterate through the form's elements and add to the onclick function. But due to the fact that in my last iteration currentOnClick is null this does not run as expected. I want to preserve each of the elements onclick methods and play them back in the new fuction Im creating.
What I want:
When input1 is clicked, alert "hello" then alert "hello2"
When Input2 is clicked, alert "hello2"
When Input3 is clicked, alert "hello2"
© Stack Overflow or respective owner