3

How can I change onclick behavior of button dynamically using javascript?

Here is what I meant:

I have following buttons:

<button class="num" onclick="getval(0)">0</button>
<button class="num" onclick="getval(1)">1</button>
<button class="num" onclick="getval(2)" >2</button>
<button class="num" onclick="getval(3)" >3</button>

function getval(){

...............

}

function getvalNew(){

..............

}

How can I make the buttons to switch from getval() to getvalNew() and reset it again?

3
  • 2
    It's easier if you don't use inline event handlers. For more information about event handling see quirksmode.org/js/introevents.html. Commented Jun 24, 2013 at 14:15
  • 1
    see @FelixKling's comment for why not to use inline event handlers, but if you have to, you could try using js to change the onclick attribute of the element. I'm a bit rusty with pure js but you could try something like jQuery('button.num').attr('onclick', 'myFunc(1)'); if you were to use jQuery. Commented Jun 24, 2013 at 14:15
  • A simple switch statement with a different variable or array or global true falses would work. You can also just onclick do a this. and change the onclick attr to be the opposite function. Commented Jun 24, 2013 at 14:16

6 Answers 6

3

Here's an approach, based on my blank.html template.

Note: in setAllFunc3, you could attach several handlers to the one element. You can also remove them selectively. See another member's note about getAllByClassName.

Also note: by attaching the handler, we get access to the this var. This means we know which element triggered the call. I have simply extracted the text from the button. You could instead get the value for an attribute, that you then use in the handler. Probably something for you to discover a little later. :)

<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
function toggleClass(element, newStr)
{
    index=element.className.indexOf(newStr);
    if ( index == -1)
        element.className += ' '+newStr;
    else
    {
        if (index != 0)
            newStr = ' '+newStr;
        element.className = element.className.replace(newStr, '');
    }
}
function forEachNode(nodeList, func)
{
    var i, n = nodeList.length;
    for (i=0; i<n; i++)
    {
        func(nodeList[i], i, nodeList);
    }
}

window.addEventListener('load', mInit, false);

function mInit()
{
}

function getval(inputVar)
{
    alert(inputVar + " was passed to getval");
}

function getvalNew(inputVar)
{
    alert("getvalNew(" + inputVar + ")");
}

function setAllFunc1()
{
    var tgtButtons = document.getElementsByClassName('num');
    var i, n = tgtButtons.length;
    for (i=0; i<n; i++)
        tgtButtons[i].setAttribute('onclick', 'getval(' + i + ')' );
}

function setAllFunc2()
{
    var tgtButtons = document.getElementsByClassName('num');
    var i, n = tgtButtons.length;
    for (i=0; i<n; i++)
        tgtButtons[i].setAttribute('onclick', 'getvalNew(' + i + ')' );
}

function myFunc3()
{
    var clickedBtn = this;
    var btnText = clickedBtn.innerHTML;
    alert("You clicked the button labelled: " + btnText);
}

function setAllFunc3()
{
    var tgtButtons = document.getElementsByClassName('num');
    var i, n = tgtButtons.length;
    for (i=0; i<n; i++)
    {
        tgtButtons[i].removeAttribute('onclick');
        tgtButtons[i].addEventListener('click', myFunc3);
    }
}

</script>
<style>
</style>
</head>
<body>
    <button class="num" onclick="getval(0)">0</button>
    <button class="num" onclick="getval(1)">1</button>
    <button class="num" onclick="getval(2)">2</button>
    <button class="num" onclick="getval(3)">3</button>
    <hr>
    Simple method - using attributes
    <input type='button' onclick='setAllFunc1()' value='set all to "getval()"'/>
    <input type='button' onclick='setAllFunc2()' value='set all to "getvalNew()"'/>
    <hr>
    Better method - using addEventListener
    <input type='button' onclick='setAllFunc3()' value='set all to "myFunc3()"'/>
</body>
</html>
Sign up to request clarification or add additional context in comments.

Comments

2
function getval() {
    ........
    var buttons = document.getElementsByClassName("num");
    for (i=0;i<buttons.length;i++){
        buttons[i].onclick = function(){
            getvalNew();
        }
    }
}

And vice versa for the other function. At least, this should work....

Comments

2

you can do something like this:

code

$(".num").on("click", function () {
    if ($(this).hasClass("getval")) {
        $(this).removeClass("getval").addClass("getvalnew");
        //do what you need here 
        alert("getVal");
    } else {
        $(this).removeClass("getvalnew").addClass("getval");
        //do what you need here 
        alert("getValNew");
    }
});

FIDDLE

http://jsfiddle.net/ygqrU/

Comments

2

You can do this with single liner JQuery syntax with your conditional statements when you want to change the function mapping.

//bind all
$('.num').bind('click', getValNew());

//Unbind all
$('.num').unbind('click');

Comments

1

In case the browser does not support getElementsByClassName, this is an alternative:

var elems = document.getElementsByTagName('button');
for (i=0;i<elems.length;i++) {
    if(elems[i].className == "num") {
        elems[i].onclick = function(){
        getvalNew();
    }
}

Comments

0

Maybe something like this:

.

var button = document.getElementsByClassName("num")
// You could also do: var button = document.getElementsByTagName("button")

function set() { // Change all the buttons onclick event to getvalNew
    for (i = 0; i < button.length; i++) {
        button[i].onclick = function() {
            getvalNew(i)
        }
    }
}

function reset() { // Change all the buttons onclick event back to getval
    for (i = 0; i < button.length; i++) {
        button[i].onclick = function() {
            getval(i)
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.