For example:

<!DOCTYPE html> <html> <head> <script type="text/javascript" src="js/calkulator3.js"></script> <link href="css/calculator1.css" rel="stylesheet" type="text/css"/> <title>test</title> </head> <body> <div class="mesto"> <div id="panel1" class="panel"> </div> <div class="knopki"> <input class="botom_1" type="button" value="1" id="a1" onClick="change"> <input class="botom_2" type="button" value="2" id="a2" onclick="change()"> <input class="botom_3" type="button" value="3" id="a3" onclick="change()"> <input class="botom_4" type="button" value="4" id="a4" onclick="change()"> <input class="botom_5" type="button" value="5" id="a5" onclick="change()"> <input class="botom_6" type="button" value="6" id="a6" onclick="change()"> <input class="botom_7" type="button" value="7" id="a7" onclick="change()"> <input class="botom_8" type="button" value="8" id="a8" onclick="change()"> <input class="botom_9" type="button" value="9" id="a9" onclick="change()"> <input class="botom_0" type="button" value="0" id="a0" onclick="change()"> </div> </div> </body> </html> 

In order not to create ten different functions, you can create one that will determine the id of the pressed button and pull the value out of this ID. How to do it?

    2 answers 2

    Use event delegation .

    The point is this - we hang the click event handler on the element that is the parent of your buttons. The event object is passed to this handler. The event object has a target property, which is a link to the button object on which the click was made. A simple example .

    • jQuery example - Sergiks
    • And I made a parameter in the change function, and I also passed my number from each button) - Boot
    • where so many good people come from - Stasyan
    • Generally figured out thanks guys - Stasyan

    Here is a sample code in the sandbox:

     function give(val) { var obj = document.getElementById('block'); obj.innerHTML = val; } 
     button { width: 150px; margin: 5px auto; text-align: center; padding: 3px; } #block { background: black; color: white; padding : 5px; } 
     <button id="1" onclick="give(this.id)">Click ME!</button> <button id="2" onclick="give(this.id)">Click ME!</button> <button id="3" onclick="give(this.id)">Click ME!</button> <button id="4" onclick="give(this.id)">Click ME!</button> <button id="5" onclick="give(this.id)">Click ME!</button> <div id=block></div>