Enter key javascript keypress not working - javascript

I've got a bit of Javascript which the end goal is for whenever the "enter" key is pressed, a message is appended to my unordered list. Right now, any key that is pressed is appended rather than it just being the "enter" key. For example if I typed "Y", that would be submitted on the press of any other button. Obviously, all I want is data thats been typed into the text-box, submitted through "enter".
My HTML:
<ul id="messagebox" >
</ul>
<div>
<input type="text" id="typetextbox" maxlength="120" autocomplete="off" />
<button type="submit" id="submit" onblur="submit"> </button>
</div>
Here is the button trigger piece of Javascript:
$(document).ready(function(){
$('#typetextbox').keypress(function (e){
if(e.keyCode == 13 );
$('#submit').click();
});
});
And here is the Javascript that works for appending the messages:
$(document).ready(function(){
$('#submit').click(function(){
var message = $('#typetextbox').val();
$('#messagebox').append(message + "<br/>");
$("#typetextbox").val("");
});
});
Why isn't it singling out just the Enter button to submit?

keyCode is actually a property of the event, so you have to use e.keyCode.
Also you were calling if(keyCode == 13 );: that semicolon (;) right after the closed parenthesis, ends the if-statement immediately, so the next line of code is always executed.
Here is the correct code:
$('#typetextbox').keypress(function (e){
if(e.keyCode == 13 ) $('#submit').click();
});
To append the message to the ul element you should create a li element first, then append it to the ul element.
Here is the correct code:
$('#submit').click(function() {
var message = $('#typetextbox').val();
if (message.replace(/ /g, '')) // If the text is not empty (e.g. nothing or only spaces)
$('#messagebox').append( $('<li>', {text: message}) );
$("#typetextbox").val("");
});
By the way, you don't need the $(document).ready function to do this. Just put your script after the textarea in the dom and it will work fine.
HERE'S THE FIDDLE: http://jsfiddle.net/t7q4j/1/

update html code as
<div>
<input type="text" id="typetextbox" onkeypress="return keyPress(event)" maxlength="120" autocomplete="off" />
<button type="submit" id="submit" onblur="submit"> </button>
</div>
java script implementation:
for every keypress the function keyPress(event) will be called.
the function definition can be
var keyPress = function(e){
if(e.keyCode == 13){
send();
}
return true;
}
the function send consists of code for updating the message box

Try below code, it's working properly.
$(document).on("keypress", function (event) {
if (event.keyCode === 13) {
alert('You hit me')
}
})

Related

How to trigger an event when use enter key for html

I want to send message when I use the enter key but it not working
for my html
<form id="form">
<textarea type="text"></textarea>
<input type="submit" value="Send">
</form>
for my js
const sub = document.getElementById('form');
// send message when hit
sub.addEventListener('submit', send);
// use enter to send message
sub.addEventListener("keypress", (event)=> {
if (event.keyCode === 13) {
send();
}
});
function send(event) {
Also, I keep getting 'keyCode' is deprecated this error message
This is not working, someone help? Thank you in advance!
I have made adjustment to your code and added the event.preventDefault(). The PreventDefault() is used to prevent the default action belonging to that even from happening.
I Have also used the event.which to get the keycode of the enter key
const sub = document.getElementById('form');
// send message when hit
sub.addEventListener('submit', send);
// use enter to send message
sub.addEventListener("keypress", (event)=> {
if (event.which === 13 ) {
//this will prevent the normal behavior of going to a new line when the enter button is pressed
e.preventDefault()
send();
}
});

Jquery: How do I get the user's input as they type

I want to be able to get the user's input to be able to validate it and see if it is a key that I want to appear or use. I don't want the full value of what is in the input, just the specific key they are entering.
I have done it in Javascript by using this code but it does not work the same in Jquery. Thanks!
<input type="text" id="a">
$("#a").on('input', function(e){
var charval = String.fromCharCode(e.Keycode);
alert(charval);
});
The alert should show the key that was pressed.
DEMO:
$("#a").on('input', function(e){
var charval = String.fromCharCode(e.Keycode);
alert(charval);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="a">
Consider this:
document.getElementById('f').addEventListener('keyup', function(e) {
document.getElementById('out').textContent = e.keyCode;
})
<input type="text" id="f">
<p id="out">Hi</p>
You'll see keyCode of the last button pressed. You can also add an alert inside a listener if you wish so.
Change e.keycode to e.which
$("#a").on("keypress", function(e){
var charval = String.fromCharCode(e.which);
alert(charval);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="a">
Just fixed your code to work :
$("#a").on('keyup', function(e){
var charval = String.fromCharCode(e.which);
alert(charval);
});

Pressing 'enter' on a input type="text", how?

I am facing a problem I can not solve JQuery Javascript. Can you help me and help me understand.First here is my code :
(...)
<script type="text/javascript">
// Autocomplete suggestions
$(function () {
$("#autoCompInput").autocomplete({
source: "/Suggestions",
minLength: 3,
select: function (event, ui) {
if (ui.item) {
$("#autoCompInput").val(ui.item.value);
$("form").submit();
}
}
});
});
// Provide search results
$(function () {
$("#autoCompSearch").click(function () {
var searchParameters = $("#autoCompInput").val();
var jsonData = JSON.stringify(searchParameters, null, 2);
window.location = "/Search?criteria=" + searchParameters;
});
});
</script>
(...)
<input class="ui-autocomplete-input" id="autoCompInput" role="textbox" aria-haspopup="true" size="50" autocomplete="off" aria-autocomplete="list" value = "#ViewBag.SearchInfo"/>
<a id= "autoCompSearch" href = "#" ><img src="#Url.Content("~/Content/Menu/Images/magnifier.png")" alt="Search" /></a>
(...)
With this code I can't use the 'Enter' key to execute my search. When the user is in the input autoCompInput I would like to be able to detect if he press 'enter' and launch the submit. I read I must add a onkeyup="onKeyPressed(event)" event but I don't understand how to write the javascipt associated with the command. I tried but without success... Do you have a solution for me?
Thank you,
You should bind the keypress event to your input
$("#autoCompInput").bind("keypress", {}, keypressInBox);
function keypressInBox(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) { //Enter keycode
e.preventDefault();
$("yourFormId").submit();
}
};
With similar HTML:
<input type="text" id="myTxt" />
<input type="submit" id="mySubmit" />
This script (which uses the latest jQuery 1.7.2) should do it:
$('#mySubmit').click(function() {
alert('Submitted!');
return false;
});
$('#myTxt').on('keyup', function(e) {
if (e.keyCode === 13) {
$('#mySubmit').click();
}
});
Here's a working example.
To assign a keyup event in jquery
$("#autoCompInput").keyup(function(event) {
if (event.keyCode==13) {
alert('enter key');
}
});
I think there is a better and more standard solution to this type of problem.
you can have a GET form around those inputs and whenever you press enter on any input inside that form, it will be submitted to whatever is in the action attribute of the form. This is how it would look like (I took your code but I am removing the bits irrelevant for my answer):
<form id="idForJqueryOnly" action="/Search" method="GET">
<input type="text" name="criteria" value="someuserinput"/>
<button type="submit"><img src="...")" alt="Search" /></button>
</form>
This is standard browser behaviour. So, what the form does? when submitted the browser creates a URL like this:
http://yourserverguesedfromthecurrenturl/Search?criteria=someuserinput
What happened is that the browser took all the inputs with name and value (and not disabled) from the form and serialized them into url form.
Now, the submit event can be triggered by pressing enter on any of the inputs inside, including buttons as long as the buttons don't have the attribute type="button".
If you wanted to do more things with the data with javascript before going to the search page, you can do this with jquery:
$("#idForJqueryOnly").submit(function(){
// here you can do stuff like serialize the form, or sanitize the input of tue user.
var data = $("#idForJqueryOnly").serialize();
$("[name=criteria]").val($("[name=criteria]").val().customSanitizeMethod());
// if you return false, the form will not submit, say, for validation errors:
return customValidator.isFormValid("#idForJqueryOnly");
})

Make a link 'enter-clickable'

If you have a normal form:
<form method='post' action='#'>
<input type='text' name='#' />
<input type='submit' value='Submit />
</form>
Then you can fill in the input field, and press enter. However, I am using a link to do my work so:
<form method='post' action='#'>
<input type='text' name='#' />
<a href='#' class='button' onclick='get_form(this).submit();'>Submit</a>
</form>
That works like a charm, however, I want it to inherit the 'enter-clickable' that the normal submit field has. Is that possible through some javascript?
$('#your_input_textfeild_id').keypress(function(e) {
//check if enter is pressed
if(e.keyCode == 13) {
//click your link
$('#your_submit_link_id').click();
}
});
try this:
<script>
document.getElementById('TEXTBOXID').onkeypress = function(e){
var evt = e || window.event;
if(evt.keyCode == 13){
get_form(this).submit();
}
}
</script>
I think the correct way to do this is to actually include a
<input type="submit" >
which you can then style to be hidden. Alternatively, just style the submit element to look the way you want. My reason for this is that the browser looks for that submit element and that's how the enter key gets assigned to submit the form. And I somehow think it's better to let the browser handle matters like that rather than using JavaScript to capture a keypress event.
You may try this
document.getElementById('my_input').onkeypress = function(e)
{
var event = e || window.event;
if(event.keyCode == 13 && this.value!="")
{
form = this.parentNode;
if(form.tagName.toLowerCase() == "form")
{
form.submit();
}
}
}
You have to add an id to your text box and replace my_input with it.

Write to textarea when enter key is pressed?

I have a textarea, which will handle output, and a textfield which will handle user input.
Focus will be entirely on the input field.
I can't make it so that the user input field will add text when the form is submitted (enter key is pressed). It will only work if there is a button and this is clicked. How do I solve this issue?
Below is the code i'm trying for the enter key submit.
<html>
<head>
<script type="text/javascript">
function addtxt(input) {
var obj=document.getElementById(input)
var txt=document.createTextNode("blah blah")
obj.appendChild(txt)
}
</script>
</head>
<body>
<textarea id="textarea1"></textarea>
<br><input type="text" onSubmit="addtxt('textarea1');">
</body>
</html>
This will do the job. Also, you should deal with the value property of the textarea rather than appending text nodes to it: if the user changes the textarea's value at all, changing its child nodes afterwards will have no effect. If you want the textarea to be read-only, add a readonly attribute: <textarea id="textarea1" readonly></textarea>.
<script type="text/javascript">
function inputKeyDown(evt, input) {
if (evt.keyCode == 13) {
var textarea = document.getElementById("textarea1");
textarea.value += "\n" + input.value;
input.value = ""; // I'm guessing you may want this
return false;
}
}
</script>
<input type="text" onkeydown="return inputKeyDown(event, this);">
Instead of submit, try using the keypress event. Detect when the enter key is pressed, copy the data, and cancel the event (to prevent form submission). If you allow the form to submit, it will simply replace the existing page with the result of the form post.
Modifying your current code:
<html>
<head>
<script type="text/javascript">
function addtxt(e,ctl,input) {
var key;
if (window.event) {
key = event.keyCode;
} else {
key = e.which;
}
if (key == 13) {
var obj=document.getElementById(input);
var txt=document.createTextNode("blah blah");
obj.appendChild(txt);
ctl.value = '';
return false;
}
return true;
}
</script>
</head>
<body>
<textarea id="textarea1"></textarea>
<br><input type="text" onkeypress="return addtxt(event,this,'textarea1');">
</body>
</html>
Note that there may be much better ways to achieve your ultimate goal, but since you don't state what that is, this is really the best I can do. Also, I'd would definitely look at using a framework like jQuery/Dojo/Prototype and add the handlers unobtrusively.
Use the form element
<form onsubmit="addtxt('textarea1')">
<textarea id="textarea1"></textarea>
<br><input type="text" />
</form>
You can use JQuery
$('textarea#textarea1').keypress(function(e) {
if (e.keyCode == 13) { // enter
//do some stuff
}
});

Categories