Search code examples
javascriptdynamiccalculatorrecordkeystroke

How to efficiently record user typing using javascript and store in database?


new to the site so not that familiar with the set-up.

I've made a simple javascript application for personal use, which is essentially a calculator, and the output is dynamic (do not need to submit or press enter to retrieve results). I want to be able to record the calculations I make so that I can recall them at a later date should I require the need to.

in simple terms, I have an input field on my website and would like to record the keystrokes and save them to a database or file so that I may read them later.

I'm just learning javascript so if you can explain it as fully as possible that would be much appreciated!

Thanks, -John

EDIT--

Added code in it's simplest form:

<html> 
<head> 
<title>Text Summation</title> 

<script type="text/javascript"> 
function calc(A,B,SUM) { 
  var one = Number(A); 
  if (isNaN(one)) { alert('Invalid entry: '+A); one=0; } 
  var two = Number(document.getElementById(B).value);  
  if (isNaN(two)) { alert('Invalid entry: '+B); two=0; } 
  document.getElementById(SUM).value = one + two; 
} 
</script> 

<body> 
<form name="form" > 
first number: 
<input name="sum1" id="op1" value="" onChange="calc(this.value,'op2','result')" /> 
plus second number: 
<input name="sum2" value="" id="op2" onChange="calc(this.value,'op1','result')" /> 
is: 
<input name="sum" value="" id="result" readonly style="border:0px;"> 
</form> 

</body> 
</html> 

Solution

  • You can use local storage to save your calculations.

    Note that localStorage is just that, local. As in stored on the physical machine you are using. So if you were to visit this page on your laptop and do some calculations, then visit the page from your desktop, you would not see the calculations you made using the laptop.

    If you need to access the calculations from different devices, you'll need a backend (server side) solution like using php to connect to a mySql database to store and retrieve the information probly with a little ajax to keep everything asynchronous.

    If you have this need and dont want to learn php , mySql, and ajax i'd recommend Parse which is basically a super easy to use backend storage API that you can interact with using just javascript. I use parse in several projects and would be lost without it.

    But first:

    One issue with your HTML:

    1. I would pass the ids of all of the elements when calling calc() instead of two ids and one value. That way A is always the value of the first element and B is always the value of the second element. Before, A was the value of the last element you changed and B was the other element's value.

    A couple of issues with calc()

    1. I would check if either input is empty before trying to call calc() otherwise, changing the first element will alway cause an alert (because the second element is still empty).
    2. I would not continue if an input was invalid, you could set to 0, but I don't see how that would benefit you. Though, could be you have a reason for this.

    After addressing these issues, simply use local storage to store the vars after you set the result as shown below. The comments should help you understand what's happening

    If your calculations can include more than just addition, I would store another variable to keep up with the operation performed as well as the numbers.

    Here is a working jsFiddle

    function calc(A,B,SUM) { 
        //changed the onChange in your HTML to pass both ids instead of the 
        //one value and one id, this makes sure that the values are always stored
        //in the same order as the elements themselves    
        A= document.getElementById(A).value;
        B= document.getElementById(B).value;
    
        //dont continue if either field is empty
        //since you're probably not done inputting yet
        if(A=='' || B=='') return;
    
        //dont continue if enrties not valid    
        if( isNaN( Number(A) ) ){
            alert('Invalid entry for A:'+ A)
            return;
        }
        else if( isNaN( Number(B) )){
            alert('Invalid entry for B: '+ B)
            return;
        }
        A = Number(A); 
        B = Number(B); 
        document.getElementById(SUM).value = A + B;
    
        //store the calculations
        storeVars( A, B, (A + B));
    }
    
    
    function storeVars( A, B, C){
            // make sure the browser supports local storage 
            if (typeof(Storage) != 'undefined'){
    
                // create an array to hold our calculations
                var calcs = [ A, B, C];
    
                //check if we aready have some calculations saved
                if(localStorage.getItem('myCalculations')){
    
                    //if so get the saved calculations as an array
                   var myCalculations = JSON.parse(localStorage['myCalculations']);
    
                   //add the new calculations to the array then update `localStorage["myCalculations"] ` 
                   myCalculations.push( calcs  );
                   localStorage["myCalculations"] = JSON.stringify( myCalculations );
    
                }
                else{
                    //if no `myCalculations` exists in localStorage
                    //create an multidimensional array holding just the current `eventSelctd`
                    localStorage["myCalculations"] = JSON.stringify( [ calcs ] )
                }
            }
            else {
                 document.getElementById("test").innerHTML = "Sorry, your browser does not support Web Storage...";
            }
    
    }
    
    
    //this method is just to show how to retrieve calcs
    function showCalcs(){
    
            if (typeof(Storage) != 'undefined'){
    
                //check if we aready have some calculations saved
                if(localStorage.getItem('myCalculations')){
    
                    //if so get the saved calculations as an array
                   var myCalculations = JSON.parse(localStorage['myCalculations']);
    
                   //clear any previously displayed calculations
                   document.getElementById("test").innerHTML = '';
    
                   //loop through the array of calculations
                  for(var i = 0; i < myCalculations.length; i++ ){
    
                    //myCalculations is an array of arrays 
                    //access it like myCalculations[0][0] to get var `A` from above from the first set of calculations
                    var current = myCalculations[i][0]+' + '+myCalculations[i][4]+' = '+myCalculations[i][5]+'<br>';
                    document.getElementById("test").innerHTML += current;
                  }
    
                }
            }  
    }
    
    //this method is just to show how to clear the stogare
    function clearCalcs(){
      localStorage.clear();
      document.getElementById("test").innerHTML = ''
    }