What's the simplest way to have a function called whenever the user hits enter after typing in a textbox?
You'll need to listen for the keypress event. It's probably easiest to do this with delegate:
$(document.body).delegate('input:text', 'keypress', function(e) {
if (e.which === 13) { // if is enter
e.preventDefault(); // don't submit form
// do what you want here
}
});
<textarea id="text"></textarea>
$('#text').keydown(function(e){
if (e.keyCode == 13) {
alert('Enter was pressed.');
}
});
http://jsfiddle.net/dNfC2/
HTML code
<input type="text" id="txt"/>
<input type="button" id="btn" value="send"/>
jquery code
$("#txt").keydown(function(event){
if(event.keyCode == 13){
alert("enter button pressed");
$("#btn").click();
}
});
Running example here : http://jsfiddle.net/Xamkp/5/
try this:
jQuery(document).bind('keydown', 'return',function (){ /*do something*/ });
you will need a plugin:
jquery.hotkeys
Well it's rather simple to do in the form you asked:
$('#idOfTextBox').keyup(function(event){
// enter key pressed
if(event.keyCode=='13')yourFunction();
});
Take note this will still append the enter key to the box. You might wanna try keydown or keypressed if you don't want that.
Be sure to check keyUp() for more detail.
Put the <input> in a form, and write a handler for the form's submit event.
This way you're not explicitly looking for any particular key; you're just waiting for the form to be submitted normally. And in every mainstream browser, pressing enter while filling out a form will submit the form.
Note that you do not need to have a physical submit button on the screen if you don't want (in which case the enter key will likely be the only way to submit the form).
Related
I know, with jQuery, it is possible to check a checkbox, but us it possible to submit a form. Not handle the submission / submitted data, but simulate the submit button being clicked— or if possible the enter / return key being pressed?
Yes, it is possible, and you don't even need the button:
$("form").submit();
$('#submit_btn_id').click(function() {
$('#form_id').submit();
});
If you have the submit button then you can emulate by using trigger in some other event's code.
$('#submit_button_id').trigger('click');
Of course but you need to specify an even at which you want to simulate the action .
I suppose that you want it to be the press of enter key .. the code will be
$(document).keypress(function(e){
if (e.which == 13){
$("#submit").trigger('click');
}
});
$("#submit").click(function(){
// do your stuff
})
In HTML, a form can be submitted by
clicking the submit button
pressing enter when the focus is on the submit button
by pressing enter on the input field
Is there a way to find out which of the three methods was used to submit the form?
HTML doesn't have any built-in way of knowing, as far as I know. You'd have to catch the necessary events and keep the state in memory. Something like the following:
Set a bool to true when the input receives focus. Set it back to false when it loses focus.
Set a bool to true when the button receives focus. Set it back to false when it loses focus.
Subscribe to the click event on the button, set a bool to true
Subscribe to the keydown event of the keyboard, check whether it is the enter-key and set a bool to true.
Now you should have the necessary information to know what actions the user took to submit the form. jQuery should be able to help you with all these events.
Also, I believe the form is also submitted when the form has focus (so not just the button or the input) and you press enter. I'm not sure if this is the actual form having focus, or any control inside the form.
So, what you're trying to achieve will require some hacking around. Are you sure you can't provide your users the experience you want in some other way?
I would use the keypress method of jquery to capture if a user is pressing the enter key. Along with the mousedown method to capture the click. The jquery and HTML code would look like this:
HTML:
<form id="myForm">
Name<input type="text" />
Address<input type="text" />
<button id="submitBtn" type="button">Submit</button>
</form>
jQuery Code:
$('#submitBtn').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
alert('You pressed "enter" key on the submit button');
}
event.stopPropagation();
});
$('#myForm').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
alert('You pressed "enter" key in the input field');
}
event.stopPropagation();
});
$('#submitBtn').mousedown(function(event){
alert('You clicked submit');
event.stopPropagation();
});
JsFiddle
Just apply different function to each action. To prevent the form fires its default action, you have to put return false; or event.preventDeafult(); in the callback function.
see the example: http://jsfiddle.net/6krYM/
HTML:
<form>
<input type='text' id='input'>
<input type='submit' value='submit' id='submit-button'>
</form>
JavaScript:
$("#submit-button").click(function(){
alert("click on submit button");
return false;
});
$("#input").keypress(function(e){
if (e.which == 13){
e.preventDefault();
alert("press enter in text");
}
});
$("#submit-button").keypress(function(e){
if (e.which == 13){
alert("press enter on button");
}
return false;
});
I noticed that if you focus on an element that mouse clic can be triggered, the Enter keys acts like as you left click the mouse. I want to avoid this running since it comes into conflict in other pieces of my code.
In the following example if I focus on this imageButton and I clic once, the next clicks can be "done" with the Enter key, so I don't want this because this button fires a slideToggle() and shows a hidden div, so IMO it's pointless toggle this div with the keyboard.
Is there any way to make it global way?
Thank you.
Try this:
$(".myElements").keypress(function(e) {
if (e.which == 13) {
e.preventDefault();
}
});
It will stop the enter key behaviour only, allowing the other key functions to work as usual.
Listen for "keypress" and .preventDefault()
ex. with <myelm class="nokey"/>
function noKeyPressing(){
var elms = document.getElementsByClassName('nokey'),
stop = function stop(e){ return e.preventDefault(), false; },
i = elms.length;
while(--i >= 0){
elms[i].addEventListener('keypress', stop, true);
}
}
noKeyPressing()
If you just want to prevent Enter then the keyCode to look for is 13.
try
.unbind('keydown');
to disable all key events on your element
You can return false to prevent the default action.
<input type="submit" onkeypress="return false;" value="Submit" />
An other possible way i think:
$('.elems').on('click',function(){$(this).blur()});
try this code
$('body *').keypress(function (e) {
if (e.which == 13) {
e.preventDefault();
}
});
the above code will prevent pressing enter for every element in page
,You can change the selector $('body *') to something else depending to your case
JavaScript (JQuery)
$('input').keyup(function(e)
{
var code = e.keyCode ? e.keyCode : e.which;
switch(code)
{
case 38:
break;
case 40:
break;
case 13:
break;
default:
return;
}
});
HTML
<form method="post" action="/">
<input type="text" name="text" />
<button type="submit">Submit</button>
</form>
I have 2 problems:
1) The caret shouldn't move when I hit the up arrow key.
For example, in Chrome when I hit the up-key it moves the caret to the left. But I only have this problem in Chrome. It works fine in FF.
2) When I hit the enter key, I don't want the form to be submitted.
BTW, I want to get this to work with keyup and not keypress.
I'd appreciate any ideas. Thanks.
I don't think you can preventDefault() (which is what you'd need to use to stop the browser from performing the default action for a key) on the keyup event - it is fired after the default event has already occurred. See this page for more.
If you can, consider using the keydown instead.
As for stopping the form from submitting, you could bind to the submit event and return false; when the submit was not triggered by the submit button (see jQuery: how to get which button was clicked upon form submission? for how to determine this).
On the other hand, you could also bind to keypress for the form and when Enter is pressed, cancel submission the same way (untested code):
$('form').keypress(function(e){
if(e.which === 13){
return false;
}
});
Instead of break you could try return false or make it call a function and use http://api.jquery.com/event.preventDefault/
For example: case 40: function(e) {e.preventDefault;}
Also, $('form').submit(function() {return false}); would stop submissions altogether, but I'm not sure that's what you're after?
In order to prevent the form being submitted when the user presses enter you need to bind the submit function of your form and return false if the event trigger was the enter button being pressed.
for the Up/Down button press, use e.preventDefault();
The most reliable method is a combination of e.preventDefault(), e.stopPropagation() and return false;
Here's what it might look like:
var override_keys = [13, 38, 40];
$('input').keyup(function(e){
var code = e.keyCode ? e.keyCode : e.which;
if ($.inArray(code, override_keys)) {
e.preventDefault();
e.stopPropagation();
return false;
}
});
Also, to prevent the form from being submitted with the enter key you should check the form's submit event:
$('#form').submit(function(e){
var code = e.keyCode ? e.keyCode : e.which;
if ($.inArray(code, override_keys)) {
return false;
}
});
It seems like that you actually CAN stop the default for 'ENTER' while using keyup(); ... jQuery api writes about it themselves here: http://api.jquery.com/keyup/
Here's how you have to do:
$('textarea').keyup(function(e) {
// your code here
}).keydown(function(e){
// your e.which for ENTER.
});
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.