Simulate an inline onkeydown event - javascript

I have an input element which I do not control
for example:
<input tabindex="2" onkeypress="if(NotReady_Key())return;fnKeyPressNum(this,'N',0);"onkeydown="if(NotReady_Key())return;fnKeyDownNum(this,9,0);" id="someElement"/>
In internet explorer 8 and 9, I am trying to find a way to make the element perform as if the "enter" button has been pressed upon the input,
I failed to find a JS way to simulate the press
but I was thinking, is it possible to grab the inline method:
onkeydown="if(NotReady_Key())return;fnKeyDownNum(this,9,0);"
from the element, obtain the element by elementById,
and execute it as if the event actually happened?
here is what I tried so far(I am using jquery):
//get dom element
var element = $("#someElement")[0];
//simulate the event
//insert element as "this"
(function(){
fnKeyDownNum(this,9,0);
}).call(element);
but it doesn't seem to work as excpected, did I forget something?
I think that I also need to make sure other system variables are simulated other than this, to fully simulate the "ENTER" event.
what can i do?
option 2 is of course to simulate a real key press of "ENTER" right on the input, but i failed to find a way to do so in IE8/9 so far, any way would be accepted even using VBS if thats an option.
please note, I specifically need IE8 and IE9 support.

If you just need to call fnKeyDownNum with an element, give this a try:
fnKeyDownNum(document.getElementById('someElement'),9,0);
But if you need to really simulate a keypress (because, a keypress can add input to a field, and if you press enter on a form element it also has the effect of submitting the form) you will have to manage that separately.

Related

Fill an input field that is not of type text and that triggers events in CasperJS

I have to do automated tests on a website and I want to use CasperJS to learn. For proprietary reasons I can not give too much code.
Here is the example of the input that I am trying to fill:
<input data-bind="value: firstname, valueUpdate: ['blur'], css: {valid:(firstname.isValid() )} " title="" class="valid" aria-required="true" id="firstname" name="firstname">
As you can see, this input is not of type text and has no value attribute. Therefore, I can not use the casper.fill() method. Furthermore, if I enter the web page scope using evaluate() and change the input value using document.querySelector, the change will not be permanent as of the events attached to the text change on the input will not be triggered.
Here is my code:
this.waitForSelector('#memberTitle', function then(){
var testname = 'thisIsNotPermanent';
this.evaluate(function(testname){
document.querySelector('#firstname').value = testname;
}, testname);
});
If I capture the screen right after, I will see my text written in the input box. However, if I wait 500ms and take another capture, the text is gone as, I suppose, the events are triggered or just cleaned because it actually failed to trigger correctly.
The events attached to the input are of Blur, Change and Keypress.
Using CasperJS, how could I go to the lowest level possible to mimic a user using his keyboard and fully use the website's functionalities already in place?
The whole point of those tests are to work with what is in place. The idea is to not have to manually go through the JavaScript of the web site.
That's exactly what the casper.sendKeys(selector, keys) function is for which will send native keypresses and (hopefully) trigger the events on that text element:
this.waitForSelector('#memberTitle', function then(){
var testname = 'thisIsNotPermanent';
this.sendKeys('#firstname', testname);
}).wait(20, function(){
this.capture('screenshot.png');
});
<input> elements without a type attribute default to Text type.
This answer is here to complete the question from another angle. As Artjom B. mentionned, the correct way to fill an input and to trigger its events is by using the sendKeys() function. However, if you ever have a case, like mine, where the events will not trigger or will take a certain amount of time, know that you can trigger those manually.
If you use the firefox inspector tool, you will see that your input or tag will have an event attached to it marked as ev. If you select it, you will have a breakdown of all the events, in order, that are triggered.
You can see that the jQuery click() event will be called. In casperjs, from the evaluate scope you can now do this :
this.evaluate(function(){
$(".discard-answer").click();
})
From there, you can chain jQuery events, like in my case where I had to .blur().change().click();
It is important to know if the event is jQuery or not.
Hope this helps.

How to detect rightclick + cut/delete/paste/undo in javascript?

In my JavaScript/jQuery code, I have a text field that I run an event when the text changes using the keyup event. However currently I only account for changes done using the keyboard.
Is there a way I can detect when a text field text changed because the user did a right click and clicked on cut or delete or paste or undo?
Note: This needs to work in IE9, and preferably Firefox and chrome, but definitely needs to work in IE9.
Thanks
jsFiddle Demo
Use jquery to bind an input event to the element like this:
$('#myInput').bind('input',function(){
//use this for the input element when input is made
var inputValue = this.value;//for example
});
As a start, this is not really the correct way to do it. But if you react on the mouseout event of a input you will most likely get it to behave the way you want.
$('#input').mouseout(function(){
if($('#input').is(":focus"))
console.log("Right-click");
});
Though it is to note that this might not work as well on textareas since they tend to be larger and the mouse might not be outside of it when the contextmenu has been clicked.
Note: Other than #Travis J that react to all interaction, this will (probably) only trigger an event on rightclick (and regular mouseout).

How can I get the new value of a HTML text element in a key event handler, also for special keys?

Lets suppose we have a html text input element and it has text "abc" and cursor is between "b" and "c". If we press backspace key then how can we get the value "ac"?
Please note that in case of special keys KeyPress event do not fire. The only events that fire are KeyDown and KeyUp and none of them has the value after the effect of special key is applied. The effect is visible after the eventhandlers of these events exit but since we have only these two events we have to somehow get the affected/latest value inside these events.
We can go to a complex way by manually applying the effect ourselves but its very very complicated given the facts that we have to find the cursor position, write different code for different special keys and bring browser compatibility. The browser, whichever it is, is already applying the effect once the eventhandlers exit but is there some way to get that latest value in those events without manually applying it or in some other event?
Please note that I am not searching for "how to find which key is pressed". I can find that by looking at the event object inside the KeyDown or KeyUp event handlers. I want to apply the effect of the special key without using a lot of manual code.
I have already looked at Capturing HTML Text Input Key press after key has been applied?. Its talking about a different thing than my question.
My ultimate task is to have a web page with only two controls: a textbox and a button. The button is initially disabled. User can type in textbox and on every key its checked that there is some text in the textbox, if there is then button is enabled, if not then button is disabled. The difficult part is to take into consideration special keys such as delete, enter, tab, backspace.
Note: I do not want to work on the blur eventhandler of the HTML text element because it affects the tab order.
Example using jQuery. The target value is stored on the title attribute, but you could make this an ajax request, or whatever logic you need. In the following case, typing 'abc' in the text box will make the go button enabled.
HTML:
<input type="text" title="abc" id="in">
<input type="button" id="go" value="Go" disabled="disabled">
Javascript:
$("#in").keyup(function() {
if($(this).val() == $(this).attr("title")) {
$("#go").removeAttr("disabled");
}
});
JSFiddle

Detect document is in direct focus

In Javascript, how do you detect if the document is in direct focus. By direct focus, I mean you're on the document, but no form elements are focused.
What I'm trying to do here is opposite of Stackoverflow's WYSIWYG editor. Stackoverflow bolds the text when you hit CTRL+B while focus is on the textarea. I want to execute a command when the user is NOT filling out any form on the page. For example, SHIFT+N goes to the next step in my application, but still allows writing capital Ns on form textareas.
I use the Prototype framework, BTW.
There is no need to track focus, it is overcomplicating things and that doesn't pass the common sense smell test... something could go wrong if you missed just one event.
If you observe the root element of a page (document or document.body) then all events which aren't explicitly stopped will reach there and you'll be able to filter out those that started on a form element.
document.observe('keypress', function(event, element) {
if (event.findElement('input, select, textarea') == document) {
// No input was typed on.
}
});
This example doesn't filter out anchors but could do easily by adding a to the findElement call.
Why don't you use a global javascript variable as a flag ?
var isFocusedOnElement = false;
And assign an onfocus trigger to all text areas,input boxes which change it to true onfocus, and false on onBlur.
Then you can check this flag whenever you encounter they keystrokes.

jquery: when i click a div, give focus to a textbox

$('.my-button').click(function() {
$(".my-textbox").focus()
});
Before Jquery 1.4 this used to be the way to call focus to a textbox, now it doesn't work. When I click the button, I want to call focus to the textbox, what i mean by "focus", is that I want the textbox to act like it was just clicked on, so that the user will not have to click on the textbox.
.focus is supposed to do an auto click onto the textbox i want it to, why isn't it working now? it broke in Jquery 1.4. I just need to know how to do it.
It still works. See here.
reference: jQuery focus docs
As mentioned there, calling 'focus' on one element may trigger 'blur' on another - and so use 'focusin' instead.
Your code works fine for me. However, it looks like you're trying to create a clickable label for an input element. If that's the case, there's an existing element named <label> that will do the job for you, no JavaScript required:
<label for="myTextBox">I'm a label, click me</label>
<input type="text" id="myTextBox" />
Example: http://jsfiddle.net/pkk6y/
Those are class selectors not IDs - not sure if that's relevant, but they're inherently not unique - particularly in the focus function jquery may just plain refuse - try using IDs (and #mybutton, #mytextbox)
Update: The jQuery doc page points out issues with IE:
The focus event does not bubble in
Internet Explorer. Therefore, scripts
that rely on event delegation with the
focus event will not work consistently
across browsers.

Categories