pfych
pfych

Reputation: 928

Use Js to change a buttons onclick value

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!

Upvotes: 0

Views: 73

Answers (3)

jmgross
jmgross

Reputation: 2346

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

Upvotes: 0

Brijesh Bhatt
Brijesh Bhatt

Reputation: 3830

Write this:

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

FIDDLE - Inspect element to see.

Upvotes: 0

Mario Araque
Mario Araque

Reputation: 4572

You can change it using this:

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

For example:

function pressOne() {
    $("#buttonOne").attr("onclick","pressTwo()");
}

Upvotes: 1

Related Questions