0

I am writing code for a simple web application that tells your word per minute while typing. It is set up in a table and there is a button to click when you finish. This works though it wastes some time which in turn effects the result. I am trying to come up with a way to call the same function when hitting enter as it would when you press the button.

Here is my function.

function finishTest() {
    finish = new Date();
    endType = finish.getTime();
    totalTime = ((endType - startType) / 1000);
    speed = Math.round((word/totalTime) * 60);
    var totalTime1 = totalTime.toFixed(2);

    if (document.form.typed.value == document.form.textArea.value) {
        document.getElementById("correct").innerHTML = "You were able to type a  " + word + " word sentence in "
            + totalTime1 + " seconds, a speed of roughly " + speed + " words per minute!";
    }
}

Here is the table where I want the function to be called by hitting enter.

<tr>
    <td colspan=2>
        <center>
            <input id = "typed" type=text name="typed" size=45>
            <input type=button value="FINISH!"  name="finish"onClick="finishTest()">
        </center>
    </td>
</tr>
Shryme
  • 1,572
  • 1
  • 14
  • 22
Craig
  • 364
  • 1
  • 3
  • 25

3 Answers3

0

Add this in your document

$(document).keydown(function(e){
    if (e.keyCode == 13) { 
       finishTest();
       return false;
    }
});

Or if you want it specifcally to apply to that table i'm sure you could change $(document) to $("#typed")

rootsup
  • 315
  • 2
  • 17
0

You can launch your function with an eventlistener.

See:

execute function on enter key

Community
  • 1
  • 1
0

You can simply do:

document.getElementById('typed').addEventListener('keyup', function(e) {
   if (e.keyCode === 13)
       finishTest();
});

This will listen for enter in your textBox and fire your function,

See this FIDDLE for an example

Shryme
  • 1,572
  • 1
  • 14
  • 22
  • I see that this works in your fiddle. I am getting this error though "Uncaught TypeError: Cannot call method 'addEventListener' of null" – Craig Feb 04 '14 at 19:40
  • The reason is because it don't find your input, make sure that inside your getElementById you put the id of your input. If it is the right id, you could try placing all your javascript inside `window.addEventListener('DOMContentLoaded', function() { PLACE CODE HERE }` to make sure the input is create when it bind the event – Shryme Feb 04 '14 at 19:44