简体   繁体   中英

Use keyboard instead of mouse click with calculator - created using JavaScript

I am making a calculator with JavaScript.

I want to make sure that when I press a key on my keyboard it appears in the textbox without clicking on the textbox. So basically, I don't only want you to click on the calculator buttons with your mouse, but also using the keys. But how do I make sure of this? Please advise.

Following is the code:

<script>

    // toon values die aangeklikt worden in de 'uitkomst' input.
    function nmr(val){
        document.getElementById('uitkomst').value+=val;
    }

    function reken(){
    // ALS er op de = teken is geklikt >>
    // ik maak een variabele aan dat de "uitkomst" values ophaalt
        var value1= document.getElementById('uitkomst').value;
        // ik maak een variabele aan dat vervolgens met 'eval' de value execute. 
        // 'eval' is het evalueren of het executen van een string.
        var res = eval(value1);
        // toon/vul vervolgens bij de "uitkomst" de "res" variabele
        document.getElementById('uitkomst').value=res;  
    }

    // als je op de "C" button klik maakt hij de value "0"
    // en zorgt hij eigenlijk dat er niks in zit.
    function leeg(){
        document.getElementById('uitkomst').value="";
    }

</script>

<!-- Maak een gewone tabel aan en zorg voor de indeling van cijfers en andere knopjes.-->

The table for the calculator:
<table border="2" align="center">

    <tr>            
      <td colspan="3">
      <input style="background-color:black;color:white;" 
               type="text" name="uitkomst" id="uitkomst">
      </td>
      <td>
        <input type="button" class="btn1" value="+" onClick="nmr('+')" /> 
      </td>        
    </tr>

    <tr>        
      <td>
        <input type="button" class="btn1" value="1" onClick="nmr('1')" />
      </td>
      <td>
        <input type="button" class="btn1" value="2" onClick="nmr('2')"/>
      </td>
      <td>
        <input type="button" class="btn1" value="3" onClick="nmr('3')"/>
      </td>
      <td>
        <input type="button" class="btn1" value="-"onClick="nmr('-')" />
      </td>        
    </tr>

    <tr>        
      <td>
        <input type="button" class="btn1" value="4" onClick="nmr('4')"/>
      </td>
      <td>
        <input type="button" class="btn1" value="5" onClick="nmr('5')"/>
      </td>
      <td>
        <input type="button" class="btn1" value="6" onClick="nmr('6')"/>
      </td>
      <td>
        <input type="button" class="btn1" value="X" onClick="nmr('*')"/> 
      </td>        
    </tr>

    <tr>        
      <td>
        <input type="button" class="btn1" value="7" onClick="nmr('7')"/>
      </td>
      <td>
        <input type="button" class="btn1" value="8" onClick="nmr('8')" /> 
      </td>
      <td>
        <input type="button" class="btn1" value="9" onClick="nmr('9')" /> 
      </td>
      <td>
        <input type="button" class="btn1" value="&divide;" onClick="nmr('/')" />
      </td>        
    </tr>

    <tr>   
      <td>
        <input type="button" class="btn1" value=". " onClick="nmr('.')" /> 
      </td>
      <td>
        <input type="button" class="btn1" value="0" onClick="nmr('0')" />
      </td>
      <td>
        <input type="button" class="btn1" value="C" onClick="leeg()" /> 
      </td>
      <td>
        <input type="button" class="btn1" value="=" onClick="reken()" /> 
      </td>
    </tr>

</table>

To give you a potential starting point you might consider the following. The rudimentary calculator keypad below provides the basic buttons found on a typical calculator - each button on your keyboard has its own keyCode number assigned and you can access that number by inspecting the event object. These events are keyup and click in the below example - there are others but these will suffice here.

Each number button is assigned a name and a value - the name is not really required. Each function button is similarly assigned both name and value - in this instance you might make use of the name when performing your actual calculations as it might be easier to refer to the name rather than the value.

The javascript event listeners do nothing more than alert the value or keyCode but you will observe that no key when pressed will create that alert unless it is within the permitted range ( given by the array validkeys ) - this allows you to use both keyboard and mouse to act as input to your calculator. To add further function buttons inspect the console and whatever key you press should reveal the respective keyCode value.

<form id='calculator'>
   <div id='lhs'>
      <output></output>
      <section id='numpad'>
         <input type="button" name="k9" value="9" />
         <input type="button" name="k8" value="8" />
         <input type="button" name="k7" value="7" />
         <input type="button" name="k6" value="6" />
         <input type="button" name="k5" value="5" />
         <input type="button" name="k4" value="4" />
         <input type="button" name="k3" value="3" />
         <input type="button" name="k2" value="2" />
         <input type="button" name="k1" value="1" />
         <input type="button" name="k0" value="0" />
      </section>
   </div>
   <div id='rhs'>
      <section id='operations'>
         <input type="button" name="add" value="+" />
         <input type="button" name="subtract" value="-" />
         <input type="button" name="multiply" value="*" />
         <input type="button" name="divide" value="/" />
         <input type="button" name="point" value="." />
         <input type="button" name="equals" value="=" />
         <input type="button" name="clear" value="C" />
      </section>
   </div>
</form>

<script>
    document.addEventListener('DOMContentLoaded',function(event){
        const output=document.querySelector('output');

        const keyhandler=function(e){
            let key=e.keyCode;
            console.info( key );
            /*
                permissable keys:
                integers 0-9

                0   =>  48
                1
                2
                3
                4
                5
                6
                7
                8
                9   =>  57

                c   =>  67
                +   =>  107
                -   =>  109
                *   =>  106
                /   =>  111
                =   =>  187
                .   =>  190

                numpad 0-9 
                96 - 105
            */
            const validkeys=[ 48,49,50,51,52,53,54,55,56,57,67,107,109,106,111,187,190, 96,97,98,99,100,101,102,103,104,105 ];
            if( ~validkeys.indexOf( key ) ){
                /* Whatever key was pressed is in the permitted values */
                alert( key )
            }
        };
        const clickhandler=function(e){
            alert( this.value )
        };


        /* Bind event listeners - keyup and button click */
        document.addEventListener('keyup', keyhandler );

        Array.from( document.querySelectorAll('input[type="button"]') ).forEach( bttn=>{
            bttn.addEventListener('click',clickhandler)
        });
    });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM