0

I have a button

<button id="buttonOne" onclick="pressOne()">Press</button>

i was wondering if it was possible using javascript to change the

onclick="pressOne()"

to

onclick="pressTwo()"

so the button would be

<button id="buttonOne" onclick="pressTwo()">Press</button>

Thanks!

pfych
  • 850
  • 1
  • 13
  • 32
  • It would be better to contain the condition which determines which logic to run within a single function. What governs which function should be executed on click? – Rory McCrossan May 07 '15 at 08:50
  • hmmm yeah its possible.... http://stackoverflow.com/questions/13229208/javascript-add-onclick-event-programmatically – yahya el fakir May 07 '15 at 08:50

3 Answers3

1

You can change it using this:

$("#buttonOne").attr("onclick","pressTwo()");

For example:

function pressOne() {
    $("#buttonOne").attr("onclick","pressTwo()");
}
Mario Araque
  • 4,562
  • 3
  • 15
  • 25
0

Write this:

$("#buttonOne").attr("onclick","pressTwo()");

FIDDLE - Inspect element to see.

Brijesh Bhatt
  • 3,810
  • 3
  • 18
  • 34
0

You can do that like this :

document.getElementById("buttonOne").setAttribute("onclick","pressTwo()");

jsFiddle


But it would be better to add an other function which handle clicks :

<button id="buttonOne" onclick="onPress()">Press</button>

With the following javascript :

var pressOne = function() {
  ...
}

var pressTwo = function() {
  ...
}

function onPress() {
  if(..) {
    pressOne();
  } else {
    pressTwo();
  }
}

jsFiddle

jmgross
  • 2,306
  • 1
  • 20
  • 24