jQuery 'event not defined' error on simulated key press - javascript

I am currently trying to use jQuery to enter a selection from a dropdown into a text box, simulate a click to select it, press return, wait for some processing and then press return again. It's quite a nasty way of getting what I need but it's the only way I can see at the moment. Here is the code:
$('#fav').change(function()
{
$('#contract_input').val($('#fav').val());
$('#contract_input').trigger('click');
e = jQuery.Event("keypress");
e.which = 13;
$('#contract_input').trigger(e).delay(500).trigger(e);
}
The issue I am having is that IE8 is giving an error on the page:
'Event' is not defined
The click seems to work, it's just the return that does not.
Any ideas?

Consider using keydown instead of keypress and in IE you could try setting e.keyCode instead of e.which.
e.g.
e = jQuery.Event("keydown");
e.keyCode = 13;
$('#contract_input').trigger(e).delay(500).trigger(e);

Edit again:
$('#contract_input').keypress(function (e) { do Stuff });
Should be used instead
http://api.jquery.com/keypress/

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

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

Categories

Resources