I need to Press space Key using JavaScript Inside a TextBox after typing the string.
How can I do it inside vugen tool (Load runner) using eval js function?
can anyone guide me?
I tried inside to evaluate javascript on the object but getting an error.
var e = new KeyboardEvent('keydown',{'keyCode':32,'which':32});
object.dispatchEvent(e);
I am using Eval Js on object function in the tool and paste this script.
ERROR:
No Error it is not clicking the space key inside text box.
I also tried this code
var keyboardEvent = document.createEvent("KeyboardEvent");
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ?
"initKeyboardEvent" : "initKeyEvent";
keyboardEvent[initMethod](
"keypress", // event type : keydown, keyup, keypress
true, // bubbles
true, // cancelable
window, // viewArg: should be window
false, // ctrlKeyArg
false, // altKeyArg
false, // shiftKeyArg
false, // metaKeyArg
32, // keyCodeArg : unsigned long the virtual key code, else
0 // charCodeArgs : unsigned long the Unicode character
associated with the depressed key, else 0
);
document.dispatchEvent(keyboardEvent);
For this also no Error but the code is not clicking space inside text box.
If you are using TruClient, you could add a eval JS step. TruClient support AUT.document and AUT.window to reference the current page of the application under test.
If you are using a eval JS step on Object, then the target element can be referenced with "object" in the code of the step.
The detail inforamtion can be found from here
How does your server know you are pressing the space bar inside of your client.....
Please check the below demo with TruClient:
Related
I'm working on keyboard shortcuts for a web application and need to check if a keypress should trigger the shortcut or if it is just the user typing and should therefore not trigger the shortcut.
For example, a common pattern is to use the / or s keys to open the global search bar. Obviously this should not open the search bar if the user is typing into another input.
The ideal logic would go something like this: On keypress, check the currently focused element. If the element accepts keyboard input (can be typed into), then do nothing. If the element does not accept keyboard input, run the shortcut.
Note that checking for focusability is not enough because links and buttons are focusable, but do not accept keyboard input (in the way I mean here).
Here's what I have so far:
function acceptsKeyboardInput(element) {
return (
element.tagName === "INPUT" ||
element.tagName === "TEXTAREA" ||
element.isContentEditable
);
}
Does this approach catch every case or is there a better way to tell if an HTML element accepts keyboard input?
Will all shortcuts be more than one key? If so you can listen for input and prevent a shortcut from running with a boolean value.
var is_input = false
window.addEventListener('keydown', function (e) {
console.log(is_input)
is_input = false
})
window.addEventListener('input', function (e) {
is_input = e.constructor.name == 'InputEvent'
})
Expected output for /s while able to type would be true or false (depending on the previous is_input value) at / keypress then true at s keypress and all keys following.
Expected output for /s while not able to type would be true or false (depending on the previous is_input value) at / keypress then false at s keypress and all keys following
From what I've seen, the suggestion given in the question seems to be the best approach—with some adjustments.
The first improvement is to blacklist a set of input types that don't accept keyboard input (e.g. checkbox or radio). I find it easier and better to use a blacklist rather than a whitelist for two reasons. The first is future-proofing against newly supported input types and in case you miss one. Second and more importantly, an invalid input type defaults back to type text, which means there are an infinite number of input types that accept keyboard input.
The second change is to also include <select> elements since they can be typed into as a sort of search/quick-select functionality.
Here's the full function:
const nonTypingInputTypes = new Set([
"checkbox",
"radio",
"button",
"reset",
"submit",
"file",
]);
export function acceptsKeyboardInput(element) {
return (
(element.tagName === "INPUT" && !nonTypingInputTypes.has(element.type)) ||
element.tagName === "TEXTAREA" ||
element.tagName === "SELECT" ||
element.isContentEditable
);
}
There are a few other inputs that don't accept keyboard input but that are less widely supported by browsers (e.g. color), so I've tried to keep it to the more commonly used and widely implemented input types.
I'm trying to enable and disable a checkbox on a keypress on my webpage. I'm trying to use sessionStorage to make it last between page refreshes but not between browser sessions.
$(document).ready(function(){
var set = sessionStorage.getItem('disable');
if (sessionStorage.getItem('disable') === null){
$("#cblDoctors_3").prop('disabled', false);
} else{
$("#cblDoctors_3").prop('disabled', set);
}
console.log(set);
});
$("html").keypress(function( event ){
if(event.which == 119){ //this is the 'w' key
var box = $("#cblDoctors_3").prop('disabled');
$("#cblDoctors_3").prop('disabled', !box);
sessionStorage.removeItem('disable');
sessionStorage.setItem('disable', !box);
console.log(sessionStorage.getItem('disable'));
}
});
So everything works fine, the console logs the correct status of the storage item, but when the page reloads, once the session item is stored, the box never reactivates on page refresh even if it's supposed to. So let's say that the user 'enabled' the box after it was disabled, the console will log false, meaning: prop('disabled', false). This is the expected result. But when the page refreshes, despite the session item being false, the box will still be disabled, meaning that the page is interpreting prop('disabled', true) despite the session variable console logging 'false'. What am I missing?
The caveat here is that Storage (interface behind both LocalStorage and SessionStorage) only allows DOMString as values to be stored (when using setItem()). Quoting the doc:
storage.setItem(keyName, keyValue);
keyName
A DOMString containing the name of the key you want to create/update.
keyValue
A DOMString containing the value you want to give the key you are creating/updating.
The same is with getItem() - it either returns null, if there's no item stored under the given key, or a DOMString.
So if you run it like this:
sessionStorage.setItem('disabled', false);
... it actually casts the boolean into DOMString. That's easy to check: just run...
console.log( typeof sessionStorage.getItem('disabled') );
... and lo and behold, here's 'string' instead of expected 'boolean'.
Now, jQuery.prop actually doesn't check the type of its argument when working with disabled property. And when it's a string 'false', it just casts it to Boolean to decide whether or not it needs to drop attribute or not. And, as you surely know, Boolean('false') === true.
What to do then? One possible approach is not storing the value at all - just clear the item when it's not needed. Another is storing an empty string (as it's the only string that casts to false). In this case, decision part is trivial:
if (event.which == 119) { //this is the 'w' key
var isDisabled = $("#cblDoctors_3").prop('disabled');
sessionStorage.setItem('disabled', isDisabled || '');
}
// ...
const isDisabled = Boolean( sessionStorage.getItem('disable') );
// it'll be false for both null and ''
$('#cblDoctors_3').prop('disabled', isDisabled);
I would like to simulate a key press in JavaScript. preferably without specifying any element.
The way I would like to do it is to use .focus() on an input and then simulate a key press like the character "a".
Just the same thing that would happen if I would press the key myself.
Searching through the internet I found no solution. It might have something to do with the combination of the simulated event and an input field. Sometimes I can catch the events, but there is no input present in the input field.
Note that this should not be considered a duplicate of Is it possible to simulate key press events programmatically? because this does not solve my problem. I have already tried it.
If you have or can include jQuery, here's the easy way
With jQuery
jQuery.event.trigger({ type: 'keydown', which: 78 }); // press n key
To simulate the keypress event within an input field, use like this
var e = jQuery.Event("keydown");
e.which = 78; // n code value
e.altKey = true; // Alt key pressed
$("#inputBox").trigger(e);
Without jQuery
var kbEvent= document.createEvent("KeyboardEvent");
var initMethod = typeof kbEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";
kbEvent[initMethod](
"keydown", // event type : keydown, keyup, keypress
true, // bubbles
true, // cancelable
window, // viewArg: should be window
false, // ctrlKeyArg
false, // altKeyArg
false, // shiftKeyArg
false, // metaKeyArg
78, // 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(kbEvent);
The above code infact will not modify the input value for you, it will only simulate keystrokes
See this post for more info
How to simulate typing in input field using jQuery?
What you need is : fn.sendKeys
I wrote this answer in Is it possible to simulate key press events programmatically?, which has been updated since this question was asked (2018), and now also includes some info about updating the input element and triggering listeners (spoiler alert, it can be sometimes easy, sometimes harder, or sometimes not doable to my knowledge).
In regards to "not specifying an element", you need an eventTarget (like an element) for dispatchEvent. If you don't use any, then you're running it in the global object, equivalent to window.dispatchEvent() in the browser.
Note: when you specify an element, the event can trigger listeners in other elements (parents) as well because of event bubbling
jSignature is having canvas and it has a class. How can I validate jSignature whether I have drawn something or not ?
I have added one bind for click event.
$sigdiv.bind('click', function(e) {
$("#num_strok").val(parseInt($("#num_strok").val()) + 1);
});
Problem is even I click some corner also num_strock get increases. And for some dragging it will not increase.
I have tried in Google whether it has any built in isEmpty function is there or not. But I have not found anything.
if( $sigdiv.jSignature('getData', 'native').length == 0) {
alert('Please Enter Signature..');
}
Very late to the party... So I wanted to give some input on my findings, each related to
using $("#sigDiv").jSignature('getData', 'putSomethignInHere') function to validate the a signature is present.
Here are the options I have examined for the second attribute passed into the jSignature function:
native returns an object of objects .length == 0 when the sig box is empty, but .length > 0 when there is something in the sig box. If you want to know how many strokes just use the length of this object.
NOTE: According to the jSignature documentation:
"Stroke = mousedown + mousemoved * n (+ mouseup but we don't record that as that was the "end / lack of movement" indicator)"
base30 also returns an object. Here I looked at the information in the second index position of this object.
x = $("#sigDiv").jSignature('getData', 'base30')[1].length > 0 ? TRUE : FALSE Here x would yeild TRUE if the box has been signed and FALSE when the jSig box is left untouched.
In my case, I used the base30 attribute for validating signature complexity, not just "did the end user draw something?".
x = $("#sigDiv").jSignature('getData', 'base30')[1].length > {insertValueHere} ? TRUE : FALSE. To validate the end user actually signed in the box and gave more than a simple '.' of small 'x'. The return value of the second index yielded from base30 gets larger as the complexity. Thus, if the user did enter just a dot,
x = $("#sigDiv").jSignature('getData', 'base30')[1].length would be about 5. The yielded value just get larger and larger the more the end user draws in the box. The highest lenght I recorded during my testing was 2272. And I scribbled and scribbled in the box for all of 15 secounds.
According to the jSig documentation:
base30 (alias image/jSignature;base30) (EXPORT AND IMPORT) (VECTOR) data format is a Base64-spirited compression format tuned for absurd compactness and native url-compatibility. It is "native" data structure compressed into a compact string representation of all vectors.
image- this is a choice I would avoid for validation. It produces an object with a long string in the second index position. The last one I measured was 672 characters long. Using image produces a string regardless whether the sig box is blank or used. And to make things more unuseful, the string produced is different for a blank signature box in Chrome verse a blank signature box in FF Developer. I'm sure the image value has a use, but just not validation.
svgbase64 - this is similar to image with exceptions. Unlike image, using svgbase64 produces a long -yet shorter- string in the second position. Also, this string IS the same when I performed the Chrome verse FF Developer check. This is where I stopped my testing. So I assume you can use svgbase64 for validation.
These are my conclusions, yours may vary. Please don't hold my low reputation against me.
According to the jSignature website there is a getData function in the API. If you use the getData function on an empty signature area as reference, you could then use getData whenever you want and compare it to the empty reference. You would then be able to tell if something has been written in the signature area.
This is just a guess from my part, as I haven't used this script, but I think something like this would be able to work.
EDIT
I also found this on the website
The dom element upon which jSignature was initialized emits 'change'
event immediately after a stroke is done being added to the storage.
(In other words, when user is done drawing each stroke. If user draws
3 strokes, this event is emitted 3 times, after each stroke is done.)
Here is how you would bind to that event:
$("#signature").bind('change', function(e){ /* 'e.target' will refer
to div with "#signature" */ })
Event is emitted asynchronously through a "thread" ( setTimeout(..., 3) ) so you don't need to wrap your event handler into "thread" of any kind, as jSignature widget will go on and will not be waiting for you to be done with your custom event handler logic.
Couldn't you just set a flag variable that gets set to true on the first change event? That would indicate that something is written into the area
You can check the base30 vector if any points are there.
var isSignatureProvided=$sigdiv.jSignature('getData','base30')[1].length>1?true:false;
This worked for me, part using roch code :
it basically assigns the signature to a hidden textarea before submitting for validation:
<div id="signatureparent">
<div id="signature"></div>
<label for='signature_capture' class='error'></label>
</div>
<span style="visibility:hidden;">
<textarea name="signature_capture" class="required" id="signature_capture"></textarea>
</span>
<script>
$(document).ready(function(){
$('#submit').click(function() {
var isSignatureProvided=$('#signature').jSignature('getData','base30')[1].length>1?true:false;
if (isSignatureProvided) {
var $sigdiv = $("#signature");
var datapair = $sigdiv.jSignature("getData", "svgbase64");
var data = $('#signature').jSignature('getData');
$("#signature_capture").val(data);
}
});
});
</script>
Unfortunately no of existing answers worked for me. On my site I have two methods of inputting a signature: manual and jSignature('importData', imgBase64)
Testing of jSignature('getData', 'native') worked only for manual drawing. And nothing worked for the image way.
The solution appeared to be simple. Just test the canvas element. It probably won't work for IE9 but who cares. Here is it in TypeScript:
isSignatureBlank() {
var canvas = <any>$('#signatureElem').find("canvas")[0];
if (!canvas) return true;
this.emptyCanvas = this.emptyCanvas || document.createElement('canvas');
this.emptyCanvas.width = canvas.width;
this.emptyCanvas.height = canvas.height;
return canvas.toDataURL() == this.emptyCanvas.toDataURL();
}
Adopted from here: How to check if a canvas is blank?
Search the code in your javascript file. Check when they are hiding 'Undo Stroke' block
t.dataEngine.data.length
That will help you finding how many stroke is made to the signature panel.
Maybe try something like this (assuming your signature fields are of class 'signature')...
$('.signature').each(function (index) {
var datapair = $(this).jSignature("getData", "svgbase64");
if (datapair[1].length > 1000 ) {
// Signature is valid; do something with it here.
}
});
The best answer:
if($sigdiv.jSignature('getData', 'native').length == 0) {
alert('Please Enter Signature..');
}
produced the following error:
$sigdiv.jSignature(...) is undefined
So I would suggest using:
if(typeof($sigdiv.jSignature('getData', 'native')) != 'undefined') {
alert('Please Enter Signature..');
}
I need to change in a text input the character '.' to ',' while typing.
In IE I change the keyCode event property in the keypress event, like this
document.getElementById('mytext').onkeypress =
function (evt) {
var e = evt || window.event;
if (e.keyCode && e.keyCode==46)
e.keyCode = 44;
else if (e.which && e.which==46) {
e.which = 44;
}
};
but it seemes that in Firefox it's impossible to change characters typed in key events.
Any suggestions?
Try this. It works on all browsers:
window.onload = function () {
var input = document.getElementById("mytext");
input.onkeypress = function () {
var evt = arguments[0] || event;
var char = String.fromCharCode(evt.which || evt.keyCode);
// Is it a period?
if (char == ".") {
// Replace it with a comma
input.value += ",";
// Cancel the original event
evt.cancelBubble = true;
return false;
}
}
};
Update: Pier Luigi pointed out a problem with the above. It doesn't take care of the caret position not being at the end of the text. It will append the command to the end even if you're inserting some text to the value.
The solution would be, instead of appending a comma, to simulate a keypress event for the comma key. Unfortunately the way dispatching of synthetic events work in different browsers seems to show a lot of variety and isn't an easy feat. I'll see if I can find a nice and generic method for it.
Assume that all properties in an Event object are immutable. The DOM spec doesn't address what happens when you change those values manually.
Here's the logic you need: listen for all key events. If it's a period, suppress the event, and manually add the comma at the cursor position. (Here's a code snippet for inserting arbitrary text at the cursor position.)
You'd suppress the event in Firefox by calling event.preventDefault(); this tells the browser not to go ahead with the default action associated with this event (in this case, typing the character). You'd suppress the event in IE by setting event.returnValue to false.
If it's not a period, return early from your handler.
Technically you just want to replace all dots with commas.
document.getElementById('mytext').onkeyup = function(){
this.value = this.value.replace('.', ',');
}
If I look at the official Document Object Model Events document, mouse events fields are defined as read-only. Keyboard events are not defined there, I suppose Mozilla followed this policy for them.
So basically, unless there is some smart trick, you cannot alter an event the way you want. You probably have to intercept the key and insert the char (raw or translated) where the caret is, the way JS HTML editors do.
Does this really need to be done on the fly? If you are collecting the information to be posted to a form or submitted to a database, would it not be better to modify the data once it was submitted? That way the user never sees the confusing change.
This is possible now by intercepting and cancelling the default keydown event and using HTMLInputElement.setRangeText to insert your desired character. This would look something like this:
document.addEventListener('keydown', $event => {
if($event.code === 'Period'){
$event.preventDefault();
let inputEl = document.querySelector("#my-input");
inputEl.setRangeText(
',',
inputEl.selectionStart,
inputEl.selectionEnd,
"end"
);
}
})
setRangeText will insert text at the cursor position in a given input. The "end" string as the last argument sets the cursor to the end of the inserted content.
More info here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setRangeText