Rumel
Rumel

Reputation: 319

Can add more than one event handler with onclick

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);
}

Upvotes: 0

Views: 2473

Answers (1)

rgthree
rgthree

Reputation: 7273

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);

Upvotes: 2

Related Questions