用户在输入字段上按Enter键时如何运行函数?

时间:2014-12-12 17:48:26

标签: javascript html forms

我有一个输入字段,可以在提交时生成格式化文本。它适用于按钮,但我也想让它在用户按下Enter键时工作。

关于如何实现这一目标的任何想法? 此外,当用户点击“添加”按钮时,我想将焦点返回到文本字段。

这是我的代码:

<!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>

1 个答案:

答案 0 :(得分:2)

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

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

演示:http://jsfiddle.net/p7twLf0v/