Triggering a True Keyboard Press in Javascript/Jquery - javascript

I have seen multiple solutions and have tried them all, but none of them seem to be working for what I am trying to do.
Here is how I'm sending the key-presses right now:
$("#choice").autotype(text + "{{enter}}", {delay: 100});
It works (as in, it shows the letters in the textbox) but I still need to press enter manually, despite it being part of the line of code above.
I have also attempted using the code I found from another stackoverflow answer:
e = jQuery.Event("keypress")
e.which = 13 //choose the one you want
$("#test").keypress(function(){
alert('keypress triggered')
}).trigger(e)
(That's the raw version, I changed it a bit to fit my needs but it basically was the same).
I've done a lot of research on this but I can't figure out how to make a true keystroke... is it even possible?
For reference, the keystroke that I'm trying to automate is the enter (return) key.
Thanks.

Related

How can I get around a keypress requirement on a javascript textbox?

Hello and thanks for reading.
So I am trying to automatically log into this form using Chrome.
https://app.patientaccess.com/login
I use my own Chrome extension to do this. It's basically just a javascript file that fills in the fields automatically. I use it for a range of websites.
For example, this is my function for filling in a textbox:
function fld(param, val){try{document.querySelectorAll(param)[0].value = val} catch(e){}}
And I call it like this:
fld("input[id='loginForm-email']", "mail#myemail.com")
For most websites it works. But for the Patient Access website above, it doesn't and I think the reason is because the password textbox requires a physical keypress (or listening for a change event or something).
When I run my script, it fills in the textboxes just fine but it doesn't let me click next because, even though the textboxes appear to be filled in, the webpage knows that I haven't actually pressed any keys.
To get around it, I have to have my script fill in the form, then click in the password box, press space, delete the space I just entered and then it lets me sign in because it knows I have physically pressed a key in the password box.
So my question is how can I make my automatic sign in javascript work on this website?
I don't think a script can use keypress events to type into a textbox but that's ok because I can fill in the textbox programmatically (using the fld function above). But how can I convince the page that I have typed into the password textbox so it lets me submit the form?
I am using JavaScript as I said and I can include jQuery if needed.
Thanks.
After much trial and error, I was able to solve it with JavaScript using this:
var fireOnThis = document.querySelectorAll("[type='text']")[0]
const changeEvent = new Event('input', { bubbles: true, cancelable: true });
fireOnThis.dispatchEvent(changeEvent);
It works absolutely beautifully. I turned this into a function and all I do is run this function after automatically filling in the text field (it doesn't work before filling in the field, has to be after).
I tried many other solutions on other websites and none worked but this one does. Whee!
I got the concept from a Chrome Extension called Form Filler. I tried the extension on the form I was trying to automate and to my surprise, it filled in the form without issue. So I looked at the source code to find out how it did it and I found this:
['input', 'click', 'change', 'blur'].forEach(event => {
const changeEvent = new Event(event, { bubbles: true, cancelable: true });
element.dispatchEvent(changeEvent);
});
So I just converted that into the code in my answer and it worked a treat. So credit should really go to Hussein Shabbir, the developer of Form Filler.

Javascript won't search updated HTML

I've been doing tiny little projects to try to learn Javascript. When I was playing with Kahoot I noticed that even though it should be a different color ~25% of the time, it seems to be red the majority of the time.
I'm trying to make javascript code to put into the console that lets me automatically always choose red and then it records whether it was correct or incorrect.
To click red, I can do var red = document.getElementsByTagName("button")[0]; then red.click(), and to check if it's right or wrong I can do
if ((document.documentElement.innerText).indexOf('Incorrect') > -1) {
alert('Incorrect');
} else if ((document.documentElement.innerText).indexOf("Correct") > -1) {
alert('Correct');
}
This works... sometimes. I think I know the problem but I don't know how to fix it. The button red will disappear to display whether it was correct or incorrect, then it will pop back up.
Normally I can set the variable red, and it works, but the next time the button pops up and I set the variable again it says undefined. In order to fix this, I need to use inspect element to press "Edit HTML" then press Enter.
I think this helps because when it says undefined it's looking through an older version of the HTML, the one where the button is hidden, and when I edit the html it updates the html that the javascript is searching.
Edit: I'm bad at explaining, so here's a video on my problem: https://youtu.be/9WaIOPRny28

Autofocus input somehow catching a keypress?

I'm implementing a couple of shortcut keys for my MVC web app and I'm running into an issue. The app allows users to answer multiple choice or short answer questions, and I'd like to make multiple choice questions answerable by just pressing 1,2,3,4 etc. Here's what I have right now:
$(document).on("keypress", function (e) {
self.someKeyPressed(e);
});
[...]
someKeyPressed: function(e) {
// locate all the multiple choice buttons in this view
var buttons = this.$el.find('button');
if(_.contains(_.range(49,55), e.which) && buttons.length) {
index = e.which - 49;
var answer = $(buttons[index]).text();
this.answerQuestion(answer);
}
e.stopPropagation();
},
This works fine, except for the case when a multiple-choice question is immediately followed up by a short answer question. In this case, the same <div> used to contain the elements, is instead replaced with:
<input placeholder="answer goes here" autofocus="autofocus">
And here's where the problem is: whatever shortcut I used on my keyboard to answer the multiple choice question shows up in the as if the user had typed it in, even though that view didn't exist at the time of the keypress. I tried to wire up an event on "input keypress" and that doesn't even go off in this situation. Interestingly enough, removing autofocus fixes the issue, but unfortunately I need it for for the user experience to be pleasant.
What's going on here? Is there anything I can do to prevent the keypress from making it into the input until I'm ready?
Edit: it looks like adding e.preventDefault() right after e.stopPropagation() did the trick. Without it, the shortcut number would be typed into the input as soon as the jquery event dispatcher logic completed, but no sooner.
It looks like calling e.preventDefault() does the trick, even though I'd still love to find out one day why exactly this makes a difference.

Updating a text box with javascript

I am having some trouble with some javascript and how it can control the html "text box".
First, here's what I have;
javascript:
function UpdateOrder()
{
// enable/disable appropriate buttons
document.getElementById("reset").disabled=false;
document.getElementById("add").disabled=false;
document.getElementById("submit").disabled=false;
document.getElementById("edit").disabled=false;
document.getElementById("update").disabled=true;
// Show display box, 'DispCurOrder'
document.getElementById('all_labels').disabled=true;
}
function EditOrder()
{
// enable/disable appropriate buttons
document.getElementById("reset").disabled=true;
document.getElementById("add").disabled=true;
document.getElementById("submit").disabled=true;
document.getElementById("edit").disabled=true;
document.getElementById("update").disabled=false;
document.getElementById('all_labels').disabled=false;
}
The Idea is simple... I have some buttons and inputs to generate a 'line' of text that get's dumped to the disabled text box. If the operator notices that they made a type-o or want to change something, they click on 'edit order' and it disables all the regular buttons, and enables the text box and 'update' button. The 'update order' button reverses this.
Now, when I just use the add lines to the text box, all works well. You can see each line get appended to the text box (there's another java function that does a bunch of error checking and such, but the crux is that it takes the contents of the text box, parses it on the "\n" to an array, then appends the new line of text. It then takes the array and puts it all together as a new string and puts it back into the text box. Here is that portion without all the error checking stuff;
function AppendOrder()
{
// let's set up an error flag.
var AppendError="";
var str1=document.forms["MyForm"].DataEntry1.value;
var str2=document.forms["MyForm"].DataEntry2.value;
if( /* checking variable str1 for errors */)
{
AppendError="Error in str 1 here";
}
if( /* checking variable str1 for errors */)
{
AppendError=AppendError+"Error in str 2 here";
}
// Display the error message, if there are no errors, it will clear what was there.
$('#AppendStatus').html(AppendError);
if(AppendError=="")
{
// it's all good, update the display
// create line of text
curEntry=str1 + " -- " + str2;
// let's get the current order into a list
str=document.getElementById('all_data').innerHTML;
if(str1=="Empty")
{
// make curOrder = to 1 element array of curEntry
var curOrder=[curEntry];
}
else
{
// parse str1 into an array and parse it to curOrder.
// Then push curEntry on the end.
var curOrder=str1.split("\n");
curOrder.push(curEntry);
}
// now we should have an array called 'curOrder[]'. Let's show it
// on the web page.
$('#all_labels').html(curOrder);
}
}
Now, the problem that I'm having is that after I add a line or two (or more) to the display using the 'add' button and then go into the 'edit' mode (where the text box is enabled) and I make all my changes, the 'add' button doesn't work.
Oddly enough, when I press the 'reset' button (which is just a reset button) it then shows all the adds I did after the edit, and the edited stuff is gone.
Now... to the question... is there something I'm not understanding about the text box? Is there some trick I need to do to get it to work? Am I going about this all wrong? Should I be using a different tool for this other than the 'textbox'?
Any help is greatly appreciated!!
Greg
Found the typo in your jsFiddle.
The first thing that I did was to add:
alert('hi there');
to the very top of the script, inside the $(document).ready() wrapper. Note that on jsFiddle you cannot see the document.ready wrapper, it is invisibly included, so just put the alert at top of javascript block as I did (link to my new jsFiddle is at bottom of answer)
Next, I noticed that you are enabling/disabling several controls by referencing them individually by ID. You can reference several controls at one time if they share the same class, so I invented the class="orderentry" and added that attribute to each of those controls. This removed 8 lines of code, which made troubleshooting easier.
Then, I began deleting/undeleting. First, I deleted everything in the javascript panel except alert('hi there');, and ran the jsFiddle. The alert popped up. Great. So I used Ctrl+z to undelete everything. Next, I selected everything EXCEPT the next block of code, and deleted the selection. I ran the jsFiddle, and again the alert popped up.
I continued deleting/undeleting until I found out where the alert no longer worked -- and that revealed the offending code block. Just had to carefully study the syntax in that specific area and found the error:
$('#txtOrder').attr({'disabled':'disabled')}; <== ERROR: note final parentheses
instead of
$('#txtOrder').attr({'disabled':'disabled'}); <== CORRECT: note final parentheses
Hope this helped, good luck on the rest of your project.
Here is the corrected jsFiddle
You didn't share your HTML, so I made assumptions about what your markup looks like.
Working jsFiddle here
The above jsFiddle is a much simplified version of what you are creating. Obviously, it is very different from what you have done so that I could create it quickly.
Observe how I made certain things happen with jQuery; take what is useful and ignore the rest.
Specifically, you can see how I initially disabled the textarea control:
$('#txtArea').attr({'disabled':'disabled'});
Re-enabled the textarea control for editing, while also hiding the Edit button and displaying the Save button:
$('#txtArea').removeAttr('disabled');
$('#btnSave').show();
$(this).hide();
Importantly, this is how I ensure each addition adds to (rather than overwriting) existing content:
var ord = 'Requested By: ' + $('#txtReq').val() + '\r\n';
Very likely you already know many (most?) of the things I am pointing out, but I have no idea what you know so, again, keep the one or two things you find useful and ignore the rest. I only hope I've managed to hit on the bit that has you stumped at the moment.
I very rarely recommend W3Schools for anything, but look here for their excellent summary / reference of jQuery selectors, events, methods. (Keep hitting Next Chapter to cycle through all pages of this reference).

Sharepoint edit form using $().SPServices.SPGetCurrentUser() not displaying until I move the mouse or hit a key

I have a custom EditForm.aspx in which I am using Javascript to hide some rows for some users. In order to determine the current user, I am calling $().SPServices.SPGetCurrentUser(). My code works perfectly on one server, but on a different one, it does this weird thing -- the edit page does not display until you do something like moving the mouse or hitting a key. You just see a blank screen except for a blinking cursor where one of the text fields would be. As soon as you move the mouse or hit a key, the page displays instantly.
To narrow the range of possibilities, I removed all javascript code except this single line
<script type="text/javascript" language="javascript" src="/blah/blah/js/jquery.SPServices-0.5.8.min.js"></script>
<script type="text/javascript">
$().SPServices.SPGetCurrentUser()
</script>
from the page. Comment it out, the page works normally. Leave it in, and you get the weird behavior described above. I tested the result of the function and it provides the current user correctly. And again, on the other server, it works fine.
Ideas?
If you look at the SPServices.js file, you will notice that the function extends a few options. One of which is the fieldName. You should pass it a fieldName like maybe Title which will return the person Full Name. The problem is though, that is data does not exists, it seems to break. I dont think there is really a "returns false when empty" feature to it.
var userName = $().SPServices.SPGetCurrentUser({
fieldName: "Title"
});
SPGetCurrentUser Wiki

Categories