JavaScript Logo

Passing Parameters in Javascript onClick Event

I ran into a problem today.

I was trying to generate a bunch of input buttons with JavaScript and have each of them do something unique onClick.

The Wrong Way

The Problem

The issue is in JavaScript global variable. Since temp is a global variable, the onclick trigger sends the content of temp after the loop is all finished. Since Adam is the last value to be stored in temp, that’s what all buttons alert. The trick is to use input name as a non-global and then pass the whole input tag to the function like so:

The Right Way


Published by

Jon Kuperman

Jon Kuperman is a Programmer, Teacher and Entrepreneur. He's a Software Engineer at Twitter and lives in San Francisco, California.

Leave a Reply

Your email address will not be published. Required fields are marked *