How do you simulate a keyboard enter event in UFT - javascript

I have a web application that I am testing with HP's UFT software. Within my application,
there is a text field with an onkeydown attribute. When a key is pressed within the text field, a function is called which triggers different actions depending on what key was pressed. I am interested in the enter key. When the enter key is pressed, rows are created within the form. How can I simulate the enter key being pressed within the field?
I have tried
field1.Set Chr(13)
field1.FireEvent "onkeydown"
but it doesn't trigger the event.
I am trying aviod using the SendKeys command.

If you use device replay mode (as described in this answer) and send a vbCRLF your application will be able to see the enter key.
Setting.WebPackage("ReplayType") = 2 ''# Changes to device mode
Browser("Enter").Page("Enter").WebEdit("WebEdit").Set "a" & vbCRLF
This works (on IE) for the following sample page:
<!DOCTYPE html>
<html>
<head>
<title>Enter</title>
<script>
function okd() {
if (event.keyCode == 13)
alert("Got enter");
}
</script>
</head>
<body>
<textarea onkeydown="okd()"></textarea>
</body>

These are the some methods i have tried for simulate keyboard events and worked for me..
Set oShell = CreateObject("WScript.Shell")
oShell.SendKeys "{TAB}" ' Click Tab Key
oShell.SendKeys "{ENTER}" ' Click Enter\Return
Also i have used
Type micAltDwn + "RETURN" + micAltUp ' Click Tab Key
Type micAltDwn + "TAB" + micAltUp ' Click Enter\Return
If u Want to enter characters
oShell.SendKeys "{h}" ' Click h Key
oShell.SendKeys "{i}" ' Click i Key
Type micAltDwn + "h" + micAltUp ' Click h Key
Type micAltDwn + "i" + micAltUp ' Click i Key

WORKING FIDDLE
$(document).keyup(function (e) {
$("#my_id").keyup(function (e) {
if (e.keyCode == 13) {
alert("Enter Simulated!!!")
//your function goes here!!!
}
});
});
UPDATE:2nd demo

Related

Triggered keypress events not being captured?

I'm capturing input from a barcode scanner (which acts like keyboard input) and it works great, but I don't have access to a barcode scanner at the moment and need to test my code, so I need to simulate the barcode scanner (keyboard) input.
I thought triggering keypress events for each character would work, but it doesn't. Here's my test code:
var barcodeScannerTimer;
var barcodeString = '';
// capture barcode scanner input
$('body').on('keypress', function (e) {
barcodeString = barcodeString + String.fromCharCode(e.charCode);
clearTimeout(barcodeScannerTimer);
barcodeScannerTimer = setTimeout(function () {
processBarcode();
}, 300);
});
function processBarcode() {
console.log('inside processBarcode with barcodeString "' + barcodeString + '"');
if (!isNaN(barcodeString) && barcodeString != '') { // #todo this check is lame. improve.
alert('ready to process barcode: ' + barcodeString);
} else {
alert('barcode is invalid: ' + barcodeString);
}
barcodeString = ''; // reset
}
window.simulateBarcodeScan = function() {
// simulate a barcode being scanned
var barcode = '9781623411435';
for (var i = 0; i < barcode.length; i++) {
var e = jQuery.Event("keypress");
e.which = barcode[i].charCodeAt(0);
$("body").focus().trigger(e);
}
}
JSFIDDLE
If you type in a number quickly (like 1234), you'll see the input is captured fine. However, click the button to run my test code, and the input is not captured. The event is triggered because an alert box pops up, but barcodeString is empty!
Why isn't this working? Should I be triggering some event other than keypress?
The handler is reading the charCode but you are only setting which on the event. Set charCode, or read from which. https://jsfiddle.net/mendesjuan/bzfeuezv/1/
barcodeString = barcodeString + String.fromCharCode(e.which);
Firing Synthetic events
This is a reminder that firing synthetic events is tricky business and typically requires you to have intimate knowledge of the handlers (which is bad) so that you don't have to construct a full event object. Also, beware that not all events triggered by jQuery will actually trigger the native events and cause its default action to apply.
Simply put, triggering keypress does not actually type a character into a text field or fires event handlers not set with jQuery.
document.querySelector('input').addEventListener('keypress', function() {
console.log('standard input key press handler');
});
var e = jQuery.Event("keypress");
e.which = "a".charCodeAt(0);
$('input').keypress(function(){
console.log('jQuery input key press handler');
}).trigger('keypress', e);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input value="yo" />

how to call jquery autocomplete function on ctrl+ spacebar?

How can I call a javascript function on CTRL + Space?
function getdata() {
console.log("hello");
}
When I hit the getdata() function on CTRL + Space and gives me autosuggestion.
If user type something on my textbox like sta
User types CTRL + Space
It should give me a auto suggestions like stack, stackover, stackoverflow
In order to accept the keyboard input from CTRL + SPACE you'll need to register an event handler (http://www.quirksmode.org/js/events_tradmod.html) and then listen out for input from the user. This will read from an array of keystroke events and check whether they're true, then fire event when keys have been pressed, when they get released the events are false.
var map = {17: false, 32: false};
$(document).keydown(function(e) {
if (e.keyCode in map) {
map[e.keyCode] = true;
if (map[17] && map[32]) {
// FIRE EVENT
}
}
}).keyup(function(e) {
if (e.keyCode in map) {
map[e.keyCode] = false;
}
});
if you go to this link: cambiaresearch.com/articles/15/javascript-char-codes-key-codes, you'll find that the keycodes are all listed here. 17 and 32 is CTRL + SPACE.
check out this guide on auto_complete with JQuery. This code will be executed where the event is fired.
https://github.com/mliebelt/jquery-autocomplete-inner
Look at this answer. - https://stackoverflow.com/a/16006607/2277126
Here you have list of key codes key codes
Good luck!
Here's how I got JQuery autocomplete to show its dropdown list when the user presses Ctrl + space:
$( "#" + myElementId )
.on( "keydown", function( event ) {
// Ctrl+space opens the autocomplete dropdown
if (event.keyCode === $.ui.keyCode.SPACE && event.ctrlKey ) {
$(this).autocomplete("search");
}
});

Need to evoke an enter keypress on textarea?

I have this obfuscated webpage that contains a text-area,
When a user manually inserts text and presses Enter key while editing the text area an event that changes the DOM launches.
I need to pragmatically launch that event,
I know how to get to the text-area itself (using getElementsByName)
and I'm basically inserting text via textArea.value = ''
How do I get that event to launch?
Could you call a function when enter is pressed, and then also just call that function when you want to simulate enter being pressed?
element.addEventListener("keypress", function(event){
if (event.keyCode == 13) {
// Enter has just been pressed.
enterPressed();
}
});
function enterPressed(){
// Do whatever you do when enter is pressed.
}
// Somewhere else off in your code when you want to "trigger" the enter press event:
enterPressed();
is this what you want
document.getElementById("id_of_your_textarea").addEventListener("keydown", function(e) {
if (!e) { var e = window.event; }
e.preventDefault(); // sometimes useful
// Enter is pressed
if (e.keyCode == 13) { document.getElementById("id_of_your_textarea").value = '' }
}, false);
EDIT: based on your comment, you can use the trigger
if you can use jQuery.
$('#textArea').trigger('keydown');

JavaScript listener, "keypress" doesn't detect backspace?

I'm using a keypress listener eg..
addEventListener("keypress", function(event){
}
However, this doesn't seem to detect a backspace which erases text...
Is there a different listener I can use to detect this?
KeyPress event is invoked only for character (printable) keys, KeyDown event is raised for all including nonprintable such as Control, Shift, Alt, BackSpace, etc.
UPDATE:
The keypress event is fired when a key is pressed down and that key normally produces a character value
Reference.
Try keydown instead of keypress.
The keyboard events occur in this order: keydown, keyup, keypress
The problem with backspace probably is, that the browser will navigate back on keyup and thus your page will not see the keypress event.
The keypress event might be different across browsers.
I created a Jsfiddle to compare keyboard events (using the JQuery shortcuts) on Chrome and Firefox. Depending on the browser you're using a keypress event will be triggered or not -- backspace will trigger keydown/keypress/keyup on Firefox but only keydown/keyup on Chrome.
Single keyclick events triggered
on Chrome
keydown/keypress/keyup when browser registers a keyboard input (keypress is fired)
keydown/keyup if no keyboard input (tested with alt, shift, backspace, arrow keys)
keydown only for tab?
on Firefox
keydown/keypress/keyup when browser registers a keyboard input but also for backspace, arrow keys, tab (so here keypress is fired even with no input)
keydown/keyup for alt, shift
This shouldn't be surprising because according to https://api.jquery.com/keypress/:
Note: as the keypress event isn't covered by any official
specification, the actual behavior encountered when using it may
differ across browsers, browser versions, and platforms.
The use of the keypress event type is deprecated by W3C (http://www.w3.org/TR/DOM-Level-3-Events/#event-type-keypress)
The keypress event type is defined in this specification for reference
and completeness, but this specification deprecates the use of this
event type. When in editing contexts, authors can subscribe to the
beforeinput event instead.
Finally, to answer your question, you should use keyup or keydown to detect a backspace across Firefox and Chrome.
Try it out on here:
$(".inputTxt").bind("keypress keyup keydown", function (event) {
var evtType = event.type;
var eWhich = event.which;
var echarCode = event.charCode;
var ekeyCode = event.keyCode;
switch (evtType) {
case 'keypress':
$("#log").html($("#log").html() + "<b>" + evtType + "</b>" + " keycode: " + ekeyCode + " charcode: " + echarCode + " which: " + eWhich + "<br>");
break;
case 'keyup':
$("#log").html($("#log").html() + "<b>" + evtType + "</b>" + " keycode: " + ekeyCode + " charcode: " + echarCode + " which: " + eWhich + "<p>");
break;
case 'keydown':
$("#log").html($("#log").html() + "<b>" + evtType + "</b>" + " keycode: " + ekeyCode + " charcode: " + echarCode + " which: " + eWhich + "<br>");
break;
default:
break;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input class="inputTxt" type="text" />
<div id="log"></div>
Something I wrote up incase anyone comes across an issue with people hitting backspace while thinking they are in a form field
window.addEventListener("keydown", function(e){
/*
* keyCode: 8
* keyIdentifier: "U+0008"
*/
if(e.keyCode === 8 && document.activeElement !== 'text') {
e.preventDefault();
alert('Prevent page from going back');
}
});
event.key === "Backspace"
More recent and much cleaner: use event.key. No more arbitrary number codes!
note.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace") {
// Do something
}
});
Mozilla Docs
Supported Browsers
My numeric control:
function CheckNumeric(event) {
var _key = (window.Event) ? event.which : event.keyCode;
if (_key > 95 && _key < 106) {
return true;
}
else if (_key > 47 && _key < 58) {
return true;
}
else {
return false;
}
}
<input type="text" onkeydown="return CheckNumerick(event);" />
try it
BackSpace key code is 8
Use one of keyup / keydown / beforeinput events instead.
based on this reference, keypress is deprecated and no longer recommended.
The keypress event is fired when a key that produces a character value
is pressed down. Examples of keys that produce a character value are
alphabetic, numeric, and punctuation keys. Examples of keys that don't
produce a character value are modifier keys such as Alt, Shift, Ctrl,
or Meta.
if you use "beforeinput" be careful about it's Browser compatibility. the difference between "beforeinput" and the other two is that "beforeinput" is fired when input value is about to changed, so with characters that can't change the input value, it is not fired (e.g shift, ctr ,alt).
I had the same problem and by using keyup it was solved.
I was trying keydown and Backspace was not being captured. Switching to keyup worked for me.
addEventListener("keyup", function(event){
}
For reference, in case someone is using with .on for dynamically generated content.
$("body").on( "keyup", ".my-element", function(evt) {
// Do something
});

By Pressing Enter key move to next Textbox in ASP.Net

I have two textboxes and one Button control.....In first TextBox when press enter key moves to next textbox(Barcode) and when i press enter in barcode textbox it fires the button click event......till that its ok....
But what happening after fireing the Button click even on enter in Barcode Textbox its going back to focus on first textbox.........But i want this to stay in same Barcode TextBox to scan more barcodes.
The code is below.
<script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js">
</script>
<Head>
<script type="text/javascript">
$(function() {
$('input:text:first').focus();
var $inp = $('input:text');
$inp.bind('keydown', function(e) {
//var key = (e.keyCode ? e.keyCode : e.charCode);
var key = e.which;
if (key == 13) {
e.preventDefault();
var nxtIdx = $inp.index(this) + 1;
$(":input:text:eq(" + nxtIdx + ")").focus();
}
});
});
</script>
</Head>
You're handling keydown for every textbox.
You need to modify your selector to only handle keydown for the first textbox.
The button click is causing a postback to the server and reloading the page, which re-executes the javascript you posted including this line:
$('input:text:first').focus();
which sets focus on the first text input.
I can't offer much of a solution without the HTML, but hopefully understanding the cause can point you in the right direction.

Categories