Press the enter key in a text box with jQuery - javascript

How can I mimic pressing the enter button from within a <input>, using jQuery?
In other words, when a <input> (type text) is in focus and you press enter, a certain event is triggered. How can I trigger that event with jQuery?
There is no form being submitted, so .submit() won't work
EDIT
Okay, please listen carefully, because my question is being misinterpreted. I do NOT want to trigger events WHEN the enter button is pressed in textbox. I want to simulate the enter button being pressed inside the textbox, and trigger this from jQuery, from $(document).ready. So no method involving on.('keypress')... or stuff like that is what I'm looking for.

Use keypress then check the keycode
Try this
$('input').on('keypress', function(e) {
var code = e.keyCode || e.which;
if(code==13){
// Enter pressed... do anything here...
}
});
OR
e = jQuery.Event("keypress")
e.which = 13 //choose the one you want
$("#test").keypress(function(){
alert('keypress triggered')
}).trigger(e)
DEMO

Try this:
$('input').trigger(
jQuery.Event('keydown', { which: 13 })
);

try using .trigger() .Docs are here

Instead of using {which:13} try using {keyCode:13}.
$('input').trigger(jQuery.Event('keydown', {keyCode:13}));

Related

How to disable Enter key from pressing buttons?

I currently have a button with an onclick attribute, directing to a JS function.
After I click it with my mouse, pressing the Enter key clicks the button as well, which I want to disable.
My button:
<button onclick = "action()">Button</button>
My JS function:
function action(){
//do something
}
I tried solutions from Disable Enter Key and Disabling enter key for form, but they don't work.
How do I solve this? Should I not use onclick? I would like a solution in pure JS.
You could have an event listener listening for a keydown event and check if it's the enter key and the target your button. In that case disable the event.
Something like this should work, you can add the correct type:
window.addEventListener('keydown',(e) => {
if (e.keyIdentifier =='U+000A' || e.keyIdentifier =='Enter' || e.keyCode == 13)
if (e.target.nodeName=='BUTTON' && e.target.type=='') {
e.preventDefault()
e.stopPropagation()
return false
}
}, true);
try setting the button to .blur() or set focus to another element
<button onclick = "action();">Click this</button>
function action(){
//do something
this.blur()
}

Trigger Keypress event of a input field on keypress of another input field?

I have two input fields i want to trigger keypress of one input field on keypress of another input field.
What i have tried is
$('#example').keypress(function(event) {
var press = jQuery.Event("keypress");
var code = event.keyCode || event.which;
press.which = code ;
$('#search').trigger(press);
});
both example and search are input fields. Why i am doing so i because when i enter text in simple field it has to enter text in another field which filters search results.
Try this :
JavaScript
$('#example').on('keypress keyup keydown',function(event) {
// create the event
var press = jQuery.Event(event.type);
var code = event.keyCode || event.which;
press.which = code ;
// trigger
$('#search').val(this.value);
$('#search').trigger(event.type, {'event': press});
});
// Omit - Check if search box reacts
$('#search').on('keypress keyup keydown',function(event) {
// sample
console.log(event.type);
});
Demo here : http://jsbin.com/pebac/1/edit
Note that even if you successfully manage to trigger a keypress event this doesn't act as a real one, meaning that the char won't be appended to the input.
Guess it's like $.click()
$('#search').keypress();
If all you want to do is to copy the content of one field to the other, I'd say it's better to do $('#search').val($(this).val()); instead of triggering the keypress event on #search.

how to remove the default focus on submit button in HTML form?

I have a HTML form on my page. When i am putting some value in one of the text fields in form and press 'Enter key' the form gets submitted instantly. I think this is happening due to default focus is on submit button. But i try to remove that focus using blur() function, it is not working. I am using Chrome.
Is there any way to avoid this scenario?
All suggestions are welcome. thanks in advance.
The Submit button is not actually focused; Enter in a text field is supposed to submit the form.
You could register a handler for the submit event, and then only allow it if the Submit button was actually focused at the time submit was requested.
However, you'll be deliberately breaking the way that HTML forms work. Not everyone wants to submit the form using the One True Way of actually clicking the Submit button (also, you'll be breaking accessibility and may introduce browser-specific bugs).
No. The focus is still on the text field. Pressing enter there is supposed to submit the form (and bypasses the submit button entirely).
You can suppress the behavior using JavaScript, but since it is normal behavior for the browser, I wouldn't recommend doing so.
try this solution: replace the 'input' with 'button' and add attribute
type equals 'button' and handle the onclick event with submit javascript function
<form name='testForm'>
<input type='text' value="myName" />
<button type='button' onclick='testForm.submit()'/>
</form>
i think it works also with tag input adding the same attribute
Enjoy
Mirco
blur() is the way to go. It works like this:
<button onclick="this.blur();">some button</button>
Note that you should not use JavaScript and DOM-events using Attributes. This is just for demonstration purposes. Try to be unobstrusive.
Maybe it will help you out, the form is "supposed" to be sent with enter in the text box (HTML by design), it is no a matter of focus.
If you want to avoid it, check this out.
This is the proposed script:
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
Good luck, tell me if you need any clarification!
EDIT: I do agree with Piskvor answer, it may bring some bugs
this has nothing to do with the focus, its just the default behavior of you browser. to avoid this, you could try to cath the enter-keypress like this (Source - but there are a lot of other solutions (most working the same way, just using other events like the firms onsubmit instead of the documents onkeypress)):
function catchEnter(e){
// Catch IE’s window.event if the
// ‘e’ variable is null.
// FireFox and others populate the
// e variable automagically.
if (!e) e = window.event;
// Catch the keyCode into a variable.
// IE = keyCode, DOM = which.
var code = (e.keyCode) ? e.keyCode : e.which;
// If code = 13 (enter) or 3 (return),
// cancel it out; else keep going and
// process the key.
if (code == 13 || code == 3)
return false;
else
return true;
}
// Anonymous method to push the onkeypress
// onto the document.
// You could finegrain this by
// document.formName.onkeypress or even on a control.
window.onload = function() { document.onkeypress = catchEnter; };
Change:
<input type="text" ... >
To:
<textarea ... ></textarea>
You may need to mess around with the attributes a bit, I've left them signified as ....
try to add on the keypress event of your button this javascript function :
function ButtonKeyPress()
{
var code = (window.event.which) ? window.event.which : window.event.keyCode;
if ( code == 13 )
{
event.returnValue = false;
return false;
}
return true;
}
So, you have a form. In this form, you have a text input, and a submit button.
You get in the text input, you type some text, than you press "Enter". This submits the form.
You would like to break this normal behavior.
I think this is not a good idea : The convention says that when your in a text input and press "Enter", it submits the form. If you change this behavior, users could be (I don't find the right word, let's say ~) surprised.
Anyway, if you still want to do this, you should listen for the keypress event on the text input, and than prevent default behaviour shoud do the work.
let's say you use jQuery :
$(input[type=text]).bind('keypress', function(evt) {
if(evt.keyCode == 13) {
evt.preventDefault();
}
});
This should do it. I didn't test it, maybe I made mistakes, but you got the idea, no ?
And maybe keyup is better than keypress... I don't know very well this, not enough practice on key bindings
The easiest way is to set css style like this:
&:focus {
outline: 0 none;
}

Simulate Keypress With jQuery

Using jQuery, how can I simulate (trigger?) a KeyPress when a link is clicked? For example, when a user clicks the following link:
<a id="clickforspace" href="#">Click Here</a>
Then, by clicking the link, it would be as if they pressed the "spacebar" on their keyboard.
Something like this, I'm assuming:
$("#clickforspace").click(function(e) {
e.preventDefault();
//... Some type of code here to initiate "spacebar" //
});
Any ideas on how to achieve this?
I believe this is what you're looking for:
var press = jQuery.Event("keypress");
press.ctrlKey = false;
press.which = 40;
$("whatever").trigger(press);
From here.
Another option:
$(el).trigger({type: 'keypress', which: 13, keyCode: 13});
http://api.jquery.com/trigger/
The keypress event from jQuery is meant to do this sort of work. You can trigger the event by passing a string "keypress" to .trigger(). However to be more specific you can actually pass a jQuery.Event object (specify the type as "keypress") as well and provide any properties you want such as the keycode being the spacebar.
http://docs.jquery.com/Events/trigger#eventdata
Read the above documentation for more details.
You could try this SendKeys jQuery plugin:
http://bililite.com/blog/2011/01/23/improved-sendkeys/
$(element).sendkeys(string) inserts string at the insertion point in
an input, textarea or other element with contenteditable=true. If the
insertion point is not currently in the element, it remembers where
the insertion point was when sendkeys was last called (if the
insertion point was never in the element, it appends to the end).
This works:
var event = jQuery.Event('keypress');
event.which = 13;
event.keyCode = 13; //keycode to trigger this for simulating enter
jQuery(this).trigger(event);

Detect the cursor location

I have 25 components which includes [textarea, textfile, radio, combo, etc...] and I have written a key event so that when "ENTER" is entered, I call a function which will submit the page.
Now my page is getting submitted when I press enter, even in the textarea which should not be. So is there any way that I can not submit the page if it is pressed in the text area?
This happens only in IE7 and IE8; it works properly in all the other browser.
you could probably detect if any of the textarea, etc is not filled out/emtpy/unset. if all of them are filled out properly, send the form.
Did you attach the "key event" to the whole form? The whole DOM? if you did that's a normal behavior.
If you want the "Enter key" to submit the page when the focus is on the submit button then apply this functionality in the onsubmit event - there of course you can perform all the validation you need.
If you just want to exclude the enter key event from the text area - perform a simple check if the the focus is in the textarea that momemnt.
The default behaviour of a form is to submit if the user hits enter inside the form unless the focus is on a textarea, so what you want is the default behaviour. Remove whatever code you have that currently handles keypresses for the form and you'll have what you want.
I'm not sure if this will suit your needs, but you can disable the enter key inside the textarea with something like this:
$(document).ready(function(){
$('textarea').keypress(function(e){
var key = (window.event) ? e.keyCode : e.which;
if ( key == 13 ) {
return false;
} else {
return true;
}
})
})

Categories

Resources