I am trying to press a key on an input on my page using javascript.
Needs to be as a one line of code like:
javascript:oninputmyInput.pressKeynum1();
can this be done?
I am trying to press a key on an input on my page using javascript.
Needs to be as a one line of code like:
javascript:oninputmyInput.pressKeynum1();
can this be done?
Based on comments am posting this even jquery
is not tagged
// dummy event listener
$("input").keydown(function() { return true; });
var keyEvent = jQuery.Event("keydown");
keyEvent.keyCode = 13;
$("input").trigger(keyEvent);
with this you manually trigger keydown
event and this is for enter
event
If you are ok to use jQuery Workig JsFiddle:
// jQuery plugin. Called on a jQuery object, not directly.
jQuery.fn.simulateKeyPress = function(character) {
// Internally calls jQuery.event.trigger
// with arguments (Event, data, elem). That last arguments is very important!
jQuery(this).trigger({ type: 'keypress', which: character.charCodeAt(0) });
};
jQuery(document).ready( function($) {
// Bind event handler
$( 'body' ).keypress( function(e) {
alert( String.fromCharCode( e.which ) );
console.log(e);
});
// Simulate the key press
$( 'body' ).simulateKeyPress('x');
});
A non-jquery version that works in both webkit and gecko:
var keyboardEvent = document.createEvent("KeyboardEvent");
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";
keyboardEvent[initMethod](
"keydown", // event type : keydown, keyup, keypress
true, // bubbles
true, // cancelable
window, // viewArg: should be window
false, // ctrlKeyArg
false, // altKeyArg
false, // shiftKeyArg
false, // metaKeyArg
40, // keyCodeArg : unsigned long the virtual key code, else 0
0 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
);
document.dispatchEvent(keyboardEvent);