2

I have an input field that generates a formatted text on submit. It works well with a button, but I also want it to work when the user presses the Enter key.

Any ideas on how I can achieve this? Also, I would like to return the focus to the text field when the user clicks on the "Add" button.

Here's my code:

<!DOCTYPE html>
<html>
<head>
<title>Test</title>

<style>
.HiddenDiv{
color: red;
}
</style>

<script>
var counter = 0; //Prevents user from creating multiple nodes on submit
var limit = 5; //Amount of nodes that can be created per input field


//CREATES FORMATTED NODE FROM INPUT VALUE
function createNode(){
if (counter == limit)  {
//Do nothing
}
else {
var input = document.getElementById('textInput1').value; //Retrieves input
var newText = document.createElement("li"); //Creates the HTML node
newText.innerHTML = input; //Sets the node's value to whatever is in the input

document.getElementById("Form").appendChild(newText); //Adds the node to the div

document.getElementById('textInput1').value=""; //Clears text field after submit
counter++;
}
}

//CLEARS THE FORM IF YOU MADE A MISTAKE
function deleteNode(){
var node = document.getElementById('Form');
while (node.hasChildNodes()) {
node.removeChild(node.firstChild);
counter=0;
}
}
</script>
</head>

<body>

<form method="POST">
<input type="text" id="textInput1">
<input type="button" value="Add" onClick="return createNode()">
<input type="button" value="Clear" onClick="return deleteNode()">
</form>

<div id="Form" class="HiddenDiv">
</div>

</body>
</html>
Alejandro Gorgal
  • 193
  • 1
  • 1
  • 8
  • There are several articles already present on Stack Overflow (among other sites) about how to identify when the Enter key is pressed. See http://stackoverflow.com/q/11365632/215552 or http://stackoverflow.com/q/3777813/215552 – Heretic Monkey Dec 12 '14 at 17:53

1 Answers1

3
document.getElementById('textInput1').addEventListener('keypress', function (e) {
    if (e.which === 13) {
        e.stopPropagation();
        e.preventDefault();

        alert('Enter pressed');
    }
});

Demo : http://jsfiddle.net/p7twLf0v/

AlienWebguy
  • 76,997
  • 17
  • 122
  • 145