trouble catching enter keystroke in javascript - javascript

this seems simple, but i can't make it work.
i'm trying to catch an enter keystroke, and run some code, but when i hit enter, the page refreshes and nothing happens.
here's my script
function GetChar(event) {
var keyCode = ('which' in event) ? event.which : event.keyCode;
if (keyCode == '13') {
var cQuery = document.getElementById('searchfield').value;
var cURL = 'ProductGrid.aspx?Query=' + escape(cQuery);
document.location = cURL;
};
wheni hit enter the page is refreshed, and the search field is cleared, but it doesn't run any of the code in the if block

If your searchfield is inside a Form, this Form gets submitted, causing your code not to run.
You can either remove the Form and just use the Input-field, or you have to stop the Form-Submit by using somehting like this:
<form onSubmit="this.preventDefault&&this.preventDefault();this.returnValue=false;return false;">

Are you using keypress event? Explorer doesn't fire the keypress event for Enter...
http://www.quirksmode.org/js/keys.html

Returning false from your function could do the job.

Related

Manually triggering jquery keyup event passing wrong keycode

I have an input that I want to allow the user to save the text either by pressing enter or by clicking anywhere else on the screen. Getting the code to process when the user presses enter is no problem. But I want to process the same code by triggering the jquery keyup event when the user clicks away just as if they pressed Enter on the input box instead. The theory isn't giving me an issue, but the keycode is either not being passed correctly or interpreted correctly when clicking away. When I alert the interpreted keycode, I get a "1" which doesn't equate to any keypress. What am I doing wrong?
$(document).on("click","body",function(e){
if(e.target.id!="openInput"){ //Indicates user has clicked out away from the input
if($(".attributeEdit")[0]){ //This is a unique class added
var i = $.Event('keyup');
i.which = 13;
$(".attributeEdit").trigger(i); //Have also tried triggering off #openInput, too with no success
}
}
});
$(document).on("keyup",".attributeEdit",function(){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
do stuff;
}
else{
alert("keycode: " + keycode); //This results in a "1" every time user clicks away
}
});
I found a solution to the end objective using Hiren Raiyani's suggestion of a function call. It doesn't actually answer the original question, but since it solved my problem, I'm hoping this will be useful to others that search. I created a function to "do stuff" and that way, I can call that function both after the Enter key is pressed and after the mouse is clicked.
function doStuff(x,y){
do stuff
}
$(document).on("click","body",function(e){
if(e.target.id!="openInput"){ //Indicates user has clicked out away from the input
if($(".attributeEdit")[0]){ //This is a unique class added
doStuff(x,y);
}
}
});
$(document).on("keyup",".attributeEdit",function(){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
doStuff(x,y);
}
});

How to prevent moving to next page on clicking enter key using javascript in html?

I'am having the following code in javascript in order to navigate from textboxes and textareas. The issue is the functionality is working fine but, when clicking on enter it is navigating to next textbox, at the same time it is navigating to next page, how to prevent to navigate to next page when clicking on enter key. Can someone help me thanks.
$('input[type="text"],textarea').keyup(function(e){
if(e.which==39 || e.which==13)
$(this).closest('td').next().find('input[type="text"],textarea').focus();
else if(e.which==37 || e.which==8)
$(this).closest('td').prev().find('input[type="text"],textarea').focus();
else if(e.which==40 || e.which==13)
$(this).closest('tr').next().find('td:eq('+$(this).closest('td').index()+')').find('input[type="text"],textarea').focus();
else if(e.which==38 || e.which==8)
$(this).closest('tr').prev().find('td:eq('+$(this).closest('td').index()+')').find('input[type="text"],textarea').focus();
});
On keyDown for your text input, catch the input if it's the enter key and prevent the default behavior:
$('input[type="text"],textarea').keydown(function () {
if(event.keyCode == 13){
event.preventDefault();
}
});
If I recall correctly, keyDown is necessary to prevent the default enter action, rather than keyUp. But give both a try and see which works.

Form submitted twice using submit() on keyup

I had a jQuery / HTML code similar to this:
<form action="/SomeAction" method="post">
<input id="my-textbox" type="text" placeholder="Write something and press enter to continue..." />
</form>
<script type="text/javascript">
$(function() {
$('#my-textbox').keyup(function(e) {
var $textbox = $(this);
if ($textbox.val().length > 0 && e.keyCode == 13) {
$textbox.parent('form').submit();
}
});
});
</script>
The purpose was to automatically submit the form when the user pressed the Enter key. I regularly use Firefox so everything was OK for me until I tested in Google Chrome and Internet Explorer.
When I pressed the Enter key in the later browsers, sometimes I would get the form submitted twice. This was easy to notice because I would get duplicate entries in my DB and I'd see two POSTs using Fiddler.
After some testing, I found out that my problem was the jQuery code, since the textbox would submit automatically on enter without it, and using this code would produce a second POST in some browsers.
My questions are:
Why don't browsers smartly prevent the second form post (like Firefox did in my testing)?
Should I expect this behavior in all major browsers in all platforms?
Is there a way to improve this code so I perform the submit using JavaScript, but don't get the form submitted twice?
Why don't browsers smartly prevent the second form post (like Firefox did in my testing)?
That is the default behavior. What if you didn't have your script and the default behavior was such that the form wouldn't POST on enter.
Should I expect this behavior in all major browsers in all platforms?
Yes
Is there a way to improve this code so I perform the submit using JavaScript, but don't get the form submitted twice?
Use a global mutex variable and set it once the form POSTs - checking it on subsequent POSTs to validate. Or, return false from the keyup handler and stop the event propagation.
Some browsers will interpret an input button as a submit if there is only one button in the form. Just return false in your function to prevent the default behavior from submitting the form.
if ($textbox.val().length > 0 && e.keyCode == 13) {
$textbox.parent('form').submit();
return false;
}
Your form is being submitted right after the enter has been pressed (on keydown and before keyup fires) so you can do
$(function() {
$('#my-textbox').keydown(function(e){
if(e.keyCode==13) e.preventDefault();
});
$('#my-textbox').keyup(function(e) {
e.preventDefault();
var $textbox = $(this);
if($textbox.val().length > 0 && e.keyCode == 13) {
$textbox.parent('form').submit();
}
});
});​
A simple test.
Add boolean variable that would be set to true after first submit and use that variable in your if condition. This would prevent accidental double click.
You should also prevent double submit in the application backend (many web frameworks have built-in mechanism for doing this, it easy to come up with custom solution as well).

Simulating a click to submit a form in jQuery

Alright so I have a text field that will have a bar code scanned into said text field. It will search the database and return information in the form of a submit button. I am using this code to simulate a click on the submit button.
if($.browser.msie){
//simulate a click on the button
$("#search").keyup(function (e) {
if(e.keyCode == 13) {
$('input:submit').click();
}
});
}
The problem with this code is that it takes all of the keystrokes and then clicks the button that many times. This submit will represent data that gets written into the database, so if the bar code was abc123 it would do this action 6 times, but I just need it to do it once. How do I fix this? My code works in FF and Chrome, but not IE, which is the one I need to get this to work in. Grrr I hate IE so much!
Why do you need to "click" that submit button? Why don't you just submit the form like:
$("#search").blur(function(){
document.myform.submit();
});
Your barcode reader will do this for you.
Try to get code like this:
var keyCode = (window.event) ? e.which : e.keyCode;

HTML form with single text field + preventing postback in Internet Explorer

I have noticed a rather strange behaviour in IE.
I have a HTML form with a single input text field and a submit button
On Submit click I need to execute a client side JavaScript function that does the necessary.
Now when I want to prevent the postback in the text field (on enter key press).
I have added a key press JavaScript function that looks like this:
<input type=text onkeypress="return OnEnterKeyPress(event)" />
function OnEnterKeyPress(event) {
var keyNum = 0;
if (window.event) // IE
{
keyNum = event.keyCode;
}
else if (event.which) // Netscape/Firefox/Opera
{
keyNum = event.which;
}
else return true;
if (keyNum == 13) // Enter Key pressed, then start search, else do nothing.
{
OnButtonClick();
return false;
}
else
return true;
}
Strangly this doesn't work.
But if I pass the text field to the function :
<input type=text onkeypress="return OnEnterKeyPress(this,event);" />
function OnEnterKeyPress(thisForm,event) {
var keyNum = 0;
if (window.event) // IE
{
keyNum = event.keyCode;
}
else if (event.which) // Netscape/Firefox/Opera
{
keyNum = event.which;
}
else return true;
if (keyNum == 13) // Enter Key pressed, then start search, else do nothing.
{
OnButtonClick();
return false;
}
else
return true;
}
I am able to prevent the postback.
Can anyone confirm what is exactly happening here?
The HTML form has just one text box and a submit button.
The resultant output of the JavaScript function executed on submit is displayed in a HTML text area in a separate div.
Found out a work around for this issue.
i just found out that in IE, if,in a form, there is just one text field and one submit button, pressing enter results in form submit. However if there are more than one text boxes, IE doesn't auto postback the form on enter press, instead it fires the button's onclick event.
So i introduce a hidden text field in the form and everything works magically.
I donot even need to handle the onkeypress event for the text field.
<Form>
<input type="text" />
<input type="text" style="display:none"/>
<input type="submit" onClick="callPageMethod();return false;"/>
</Form>
This works perfectly for me!!
This is not an issue in FF, as pressing enter directly results in call to submit button's onclick event.
Hi you can also disable the default behavior.
jQuery('#yourInput').keydown(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
}
});
Cheers!
Return false in the onsubmit which is used to submit the form via javascript.
There must be some interaction with other code you haven't posted. Your code stops the form submission for me in both variants and there is no reason it shouldn't.
But trapping Enter keypresses is difficult to do properly and is likely to annoy as much as anything else. There is almost always a better way.
For example, as altCognito suggests, have ‘form.onsubmit’ return false so the form never submits in response to user interaction. Also, if you put your AJAX code (assuming that's what you're doing) in the onsubmit handler instead of onclick on a button, you can also make it so that pressing Enter has the same effect as clicking on the submit button, which the user might normally expect.
If you don't want that, there seems to be no reason to include the <form> element at all. It's perfectly valid to just have input elements sitting on their own, if you never expect the browser to submit them anywhere.
Have just come here because of a related observation with at least IE 7 and 8:
If there is only one text input and one submit button on a form and the user presses return key, IE will not include the submit button's name/value-pair in the request. Insead, only the text input's value will be there.
If I add another text input, both text inputs and the submit button's parameters are posted. The second text input can even be hidden: <input type="text" style="display:none"/>
So this is not related to events but rather to simple form submission.
It happens with GET and POST. Adding a select element to the form does not change the behavior. -- very strange.

Categories