Simulate Keypress With jQuery - javascript

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);

Related

Fill text box through keyboard events javascript [duplicate]

On the Definitive Trigger Keypress jQuery thread there is no working JSFiddle for the answer, and the code that is there doesn't work for me.
$("button").click(function () {
$("input").focus();
var e = jQuery.Event("keydown");
e.which = 77; // # Some key code value
$("input").trigger(e);
})
There's my code and here's my fiddle
http://jsfiddle.net/Z8adb/
On click, an M should appear in the input, as the input is given focus and having a keydown with the keyCode of 77 ("m") triggered on it.
Any ideas?
EDIT: My true purpose for this is to trigger an "m" hotkey on a Sublime Video in order to mute the video programmatically. This was my first step to ensure I was firing the "m" key properly, which I am with the help of Stack Overflow. However, I'm still not able to get an event to fire programmatically on the video. I think this is just a problem with Sublime Video, but I'm not sure, and anyone's views on forcing keypresses and clicks would be awesome to hear.
Using trigger you are just triggering the event with a keycode but not assigning the value to the textbox. Try this :- http://jsfiddle.net/PbHD2/
String.fromCharCode
$("button").click(function() {
$("input").focus();
var e = jQuery.Event("keydown");
e.which = 77; // # Some key code value
$("input").val(String.fromCharCode(e.which));
$("input").trigger(e);
});
$('input').keydown(function(e){
console.log('Yes keydown triggered. ' + e.which)
});
SublimeVideo is a HTML5 player, correct. If so, you can mute it by using a property, right?
$("video#yourVideoTagId").prop("muted", true);

Press "Delete" key using javascript?

Is there any way in Javascript or jquery using which we can internally click the "Delete" button to delete some text in HTML web pages?
I don't want my users to click the "Delete" button physically but I want to give them interface where when they click I will apply the "Delete" button functionality there.
You can trigger it using the keydown function:
$(function(){
var press = jQuery.Event("keyup");
press.ctrlKey = false;
press.which = 46;
$('#check').keyup(function(e){
alert(e.which);
}).trigger(press);
});
But this solution does NOT simulate a natural keypress event on the HTML element. This method only triggers the keyup event, it does not replicate the user going into the element and pressing that key. For doing that you can refer HERE.
But this dispatch event is also not globally supported.
I think applying the functionality of delete button on click of button can fullfill your requirement
Just write $("input").val("") on click of button or follow the answer of #haxxton given above, OR SEE DEMO HERE
Further to my comment on the OP.
Assuming your HTML looks something like
<p id="deleteMe">This text should be deleted</p>
<button id="deleteButton">DELETE</button
Option 1
if your intention is to remove the entire text of an element you could use
var deleteButton = document.getElementById('deleteButton');
deleteButton.onclick = function(){
var deleteItem = document.getElementById('deleteMe');
deleteItem.innerHTML = '';
}
Option 2
However, if it is your intention to only remove one character per click you could use something like
var deleteButton = document.getElementById('deleteButton');
deleteButton.onclick = function(){
var deleteItem = document.getElementById('deleteMe');
deleteItem.innerHTML = deleteItem.innerHTML.substring(0, deleteItem.innerHTML.length - 1);
}
Please visit : Is it possible to simulate key press events programmatically?
you can use the keycode as 46 insetead of
character.charCodeAt(0)
Call internally to a event is simple with jQuery:
$('#delete').click(); // call internally to 'Delete' button
It launchs the click event which contains your delete functionality.
See a demo more complete: http://jsfiddle.net/581env0c/2/

Press the enter key in a text box with jQuery

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}));

Can i simulate a key press? [duplicate]

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);

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;
}

Categories

Resources