0

The following link says I can add only one event handler per item.

Onclick vs addEventListener

I created a text box and added two functions test1() and test2(). They worked nicely but according to the link only one should work. Can you please explain what is happening here.

<!DOCTYPE html>

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

<body>

<form method="post" name="formRegister">
    <input id="namel" type="text" maxlength="5" name="txtFirstName" value="Tanvir" onclick="test1();test2();">

</form>

</body>
</html>

The js code :

function test1()
{
    alert(" alert one ");
}

function test2()
{
    var i = 12;
    alert(" alert two " + i);
}
Community
  • 1
  • 1
Rumel
  • 319
  • 1
  • 3
  • 19
  • onclick attribute value string is executed as javascript code. so 1 function call or 2 functions calls won't matter "t1(); t2()". When assigning a function handler to dom.onclick event handler through javascript, you can only assign one function handler reference e.g. dom.onclick = t1; though you can assign an anonymous function which internally invokes t1(); and t2(); – gp. May 03 '15 at 17:36

1 Answers1

2

You actually do have only one onclick handler, it's simply executing your two functions. Essentially, this is what is happening "behind the scenes":

<input id="namel" onclick="(function(event) { test1(); test2(); })()">

There are lots of reasons to not use inline events, but multiple function calls is not one of them (as you've just proved). The major reason is to keep your functionality out of your markup & presentation layer. Outside of that, you can choose what and when click events get and add/remove at your will:

var element = document.getElementBtId(namel);
element.addEventListener('click', test1);
element.addEventListener('click', test2);

// Then, later, you want to stop test2 from firing on a click, but
// keep any other handlers attached. You cannot do this [easily] when
// you've baked your onclicks into your initial markup.
element.removeEventListener('click', test2);
rgthree
  • 7,217
  • 17
  • 21