Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

incrementing the count on click of button

var index = 0;

By defualt the value of index is 0 and now i have two buttons, when i click on button 2 or 1, the value of index should get incremented. the second button on click should take the value one onwards... similarly third etc etc.

like image 865
theJava Avatar asked Dec 03 '22 08:12

theJava


2 Answers

You're going to need a function to do that:

function incrementIndex() {
    index += 1;
}

This assumes that your index variable is global.

Next what you'll need to do is wait for the click event. There are three ways to do that in JavaScript.

  1. Inline JavaScript

    <button onclick="incrementIndex()">Button 1</button>
    <button onclick="incrementIndex()">Button 2</button>
    

    This is how Hitler developed websites. Don't do this.

  2. Event Handler

    This requires you to wait until the DOM has loaded, and then "get" your two buttons somehow. If you only have two buttons on the page, you can do something like this (but only if this script comes after the HTML in your document):

    var buttons = document.getElementsByTagName('button');
    buttons[0].onclick = buttons[1].onclick = incrementIndex;
    

    Note in that example that there are no parentheses () at the end of incrementIndex.

  3. Event Listener

    The problem with event handlers is that you can only attach one function at a time. If you're going to have other JavaScript listening for button clicks, you'll have to use event listeners.

    But event listeners are a major pain in the butt because IE6-8 does it wrong, and (depending on the project) you'll probably have to code around it. At it's simplest, here's how to add an event listener in most browsers:

    var addEvent = window.addEventListener ? function (elem, type, method) {
        elem.addEventListener(type, method, false);
    } : function (elem, type, method) {
        elem.attachEvent('on' + type, method);
    };
    
    addEvent(buttons[0], 'click', incrementIndex);
    addEvent(buttons[1], 'click', incrementIndex);
    

    That is just the surface of cross-browser event listening. If you want to learn more, QuirksMode has a good series of articles on it.

like image 70
sdleihssirhc Avatar answered Dec 30 '22 13:12

sdleihssirhc


Your question is unclear, but I think you're looking for something like this...

<script type="text/javascript">
    index = 0;
    increment = function(){ index++; }
</script>
<button name="button1" onclick="increment();">Button 1</button>
<button name="button2" onclick="increment();">Button 2</button>
like image 29
Brandon McKinney Avatar answered Dec 30 '22 12:12

Brandon McKinney