2014-12-12 4 views
0

제출시 형식이 지정된 텍스트를 생성하는 입력란이 있습니다. 그것은 버튼과 잘 작동하지만 사용자가 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> 
+0

. http://stackoverflow.com/q/11365632/215552 또는 http://stackoverflow.com/q/3777813/215552 –

답변

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

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

데모 : Enter 키를 누르면 확인하는 방법에 대한 (다른 사이트들) 스택 오버플로 이미 여러 기사가 있습니다 http://jsfiddle.net/p7twLf0v/

+0

고맙습니다! 이것은 독립적으로 작동하는 것처럼 보이지만 내 코드에 통합 할 때 그렇지 않습니다. 모든 단서? 정말 도움을 주셔서 감사합니다. http://jsfiddle.net/p7twLf0v/1/ –

+1

Nevermind, 문제가 발생한 헤더에 코드가 있다는 것을 알았습니다. –

관련 문제