View Full Version : small problem changing a onclick

06-27-2012, 06:03 PM
here is what i have working

document.getElementById("myid").onclick = sale1;
that works fine but i need to have the "1" as a variable like

document.getElementById("myid").onclick = sale+count5;

sale being the name and count5 being the variable containg numbers.
i need to combine the sale with the variable and change the onclick to that.
any ideas:)

06-27-2012, 08:56 PM
There is apparently some confusion here. You are trying to assign variables as click handlers. This is how your code should look:

document.getElementById("myid").onclick = function(){
/* Do something when #myid is clicked */

For instance, if you wanted to change the value:

​document.getElementById("myid").onclick = function(){
this.value = parseInt( this.value, 10 ) + 5;

This would increment the current value by 5 when the element is clicked.

See it in action: http://jsfiddle.net/Baa8f/

06-27-2012, 09:38 PM
what i need to do is change what the onclick event does.
i need it to change a div onclick from sale1() to whatever is in the variable.
ranging from sale1 to sale33.

06-27-2012, 09:58 PM
document.getElementById("myid").onclick = eval("sale"+count5);

anytime you use eval, there is a better way

Philip M
06-27-2012, 10:02 PM
Is this what you mean?

<div id = "myid">Something here</div>

<script type = "text/javascript">

var count5 = 1; // a number determined by ?
var sale = {
sale1: function() {alert ("function sale1 activated") },
sale2: function() {alert ("function sale2 activated") },
sale33: function() {alert ("function sale33 activated") }

document.getElementById("myid").onclick = function(){
sale['sale' + count5]();


You will see that the functions are stored in an object. You could also access the functions directly from the window object but this has the disadvantage of using the global namespace, which many consider should be avoided.

document.getElementById("myid").onclick = function(){
window['sale' + count5]();

Following protracted negotiations we have come to an arrangement with the banks under which we have agreed not to supply goods to our customers on credit. For their part the banks have agreed not to sell fishing tackle.