I am trying to use jQuery code like below to execute some code on keypress for text box but I am getting error. Could you please help me here. I have even tried with keydown but facing same issue.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<style>
textarea.ex1 { background-color: white; width: 610px; height: 310px; overflow: Scroll; }
#outer { width:100%; text-align: center;} .inner { display: inline-block; }
body { background-color: gray; }
</style>
</head>
<body>
<textarea id="screen" class="ex1"></textarea>
<input type="text" id="command" style="width: 480px; height=600px;"/>
<script>
$("#command").keydown(function(event){
alert('Before keycode validation cond');
var keycode = (event.keyCode ? event.keyCode : event.which);
alert('After keycode validation');
if(keycode == '13')
{
alert('ENTER key selected');
$.get('Servlet3', function(response) {
alert(response);
appendResponse(response);
});
appendCommand();
}
});
function appendCommand() {
alert('appending command');
document.getElementById('screen').textContent = document.getElementById('screen').textContent + document.getElementById('command').value;
}
function appendResponse(response) {
alert('appending response');
document.getElementById('screen').textContent = document.getElementById('screen').textContent + response;
}
</script>
It looks like your code is working fine. Check the fiddle below. I just disabled the comments in code.
function onKeyDown(event) {
//alert('Before keycode validation cond');
var keycode = (event.keyCode ? event.keyCode : event.which);
//alert('After keycode validation');
if(keycode == '13')
{
//alert('ENTER key selected');
$.get('Servlet3', function(response) {
//alert(response);
appendResponse(response);
});
appendCommand();
}
}
if (window.addEventListener) {
window.addEventListener("keydown", onKeyDown, true);
} else if (document.attachEvent) { // IE
// alert(document); You can test this in IE
document.attachEvent("onkeydown", onKeyDown);
} else {
document.addEventListener("keydown", onKeyDown, true);
}
function appendCommand() {
//alert('appending command');
document.getElementById('screen').textContent = document.getElementById('screen').textContent + document.getElementById('command').value;
}
function appendResponse(response) {
//alert('appending response');
document.getElementById('screen').textContent = document.getElementById('screen').textContent + response;
}
textarea.ex1 { background-color: white; width: 610px; height: 310px; overflow: Scroll; }
#outer { width:100%; text-align: center;} .inner { display: inline-block; }
body { background-color: gray; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="screen" class="ex1"></textarea>
<input type="text" id="command" style="width: 480px; height=600px;"/>