basic live text input without html <input>'s - javascript

I'm trying to start a project that requires that the javascript know every word that's typed in. An example of something I would try to accomplish would be that you would type 4 + 4, the interpreter on the webpage knows what you mean, and automatically puts = 8 on to the end of that line to show it's computed it, without having to submit anything or press any button.
I've looked into the element, but I don't want to reinvent the wheel or go against what the spec says. With putting a <textarea> as input on top of a canvas, the javascript on the page can only know what is in the textbox when the user submits the text. Is there anything out there that would help with this?
Thanks in advance!

To get the value of a textarea you can just access it via the DOM:
var textArea = document.getElementById("id-of-textarea");
To the textarea you can attach different eventlisteners, and in your case I would use onkeypress
textArea.onkeypress = function () {
var ta_value = textArea.value;
alert(ta_value);
}
Of course you'd have to write your own interpreter, I wouldn't recommend running eval on the input...

try adding a hidden input element and give it the focus when the page load is complete, and use the onkeyup handler to do whatever u want.

Related

Simulate sending data to the text input field with JS

I have a task where I need to automate Sign in form authentication. For this example, I'll show you Tiktok authentication form (Mobile interface, not desktop. E-mail and password option)
If I enter text values into the fields programmatically, the Login button won't become active, and if I manually focus on the fields with a mouse click, the value disappears. These are two lines of code I run to put the value in:
let email_input = document.getElementsByName("email")[0];
email_input.value = 'sample#email.com';
I understand it needs to trigger a certain event to assign a value into it's JS model, but I can't figure out how to do it. I have tried sending change or input events onto this text field with no luck using this code:
let email_input = document.getElementsByName("email");
email_input[0].value = 'sample#email.com';
custom_event = new Event('input');
email_input[0].dispatchEvent(custom_event);
// tried also change, textInput like so:
custom_event = new Event('change');
email_input[0].dispatchEvent(custom_event);
But this does not seem to help.
So my goal is to put values into both fields Email and Password in the way it will be detected and Log in button would become active.
Any suggestion would be much appreciated
You should first focus needed input element and then execute document.execCommand with insertText command:
let email_input = document.getElementsByName("email");
email_input[0].focus();
document.execCommand('insertText', false, 'sample#email.com');
With this method input\textarea value modification should be captured by all major frameworks including Angular and Vuejs. This modification will be processed by frameworks the same way as if user pressed "Paste" option in browser main menu.
It all depends...
Who/what are you? A normal browser user? A bot? The browser author?
Because code like this is useless...
let email_input = document.getElementsByName("email")[0];
What document are you referring to? Who's document? Did you inject this instruction into the page and executed it?
You're not telling us where you're coming from, but anyway...
If you are the browser author, or you can run JavaScript macros from your browser (ie: the Classic browser) then you can do something like this...
var Z=W.contentWindow.document.querySelectorAll('input[type="password"]');
if(Z.length>0){
Z[0].value='password123';
Z=W.contentWindow.document.querySelectorAll('input[type="email"]');
if(Z.length>0){Z[0].value='email#abc.com';}
}
To automatically populate such fields, and if you also want you can SubmitButtonID.click() the submit button for as long as the isTrusted property is not tested by the website.
Continued...
Test if normal (non-custom) submit button exists and click...
Z=W.contentWindow.document.querySelectorAll('input[type="submit"]');
if(Z.length>0){
if(Z[0].hasAttribute('disabled')){Z[0].removeAttribute('disabled');} <--- Enable it if disabled
Z[0].click(); <--- automate click
}

Selenium clearing and typing in text into textarea text box [Python]

I am using Selenium to do some scraping. I used the following code to input the text into a textarea text box:
def clear_and_send_key_then_wait(element, key, sleep_time = 1):
# For some reason this does not work
# element.clear()
# This works
element.send_keys(Keys.CONTROL + "a");
element.send_keys(Keys.DELETE);
# Input text
element.send_keys(key)
time.sleep(sleep_time)
target_textbox = driver.find_element_by_xpath(
"""/html/body/div[2]/div/div[2]/div[1]/div[4]/div[1]/div/textarea""")
clear_and_send_key_then_wait(target_textbox, 'z'*100000)
Q1: Why doesn't element.clear() remove the existing text in the textbox?
Since a lot of texts have to be typed into the text box, the above method is too slow. Instead, I use the first Javascript method execute_script suggested here.
However, simply doing the following does not fill the text box.
driver.execute_script("arguments[0].value=arguments[1];",
target_textbox, "z"*100000)
The text only appears after another send_key command follows immediately after the execute_script line:
driver.execute_script("arguments[0].value=arguments[1];",
target_textbox, "z"*100000)
target_textbox.send_keys(Keys.ENTER)
Q2: Why is the subsequent target_textbox.send_keys(Keys.ENTER) required? It seems like in the link, the author does not need to send Enter key. Is it a different type of text box? If so, what are the different types of text boxes and do they all have different behaviors?
Thanks in advance!
Selenium doesn't fire any keyboard or mouse events on clear. Same happens when you set value using JavaScript. Probably the website waits for the keys event to proceed some work for the textarea's value and trigger for that is send_keys with any key.
You can try the code below, \ue007 is Enter key:
driver.execute_script("arguments[0].value=arguments[1];", target_textbox, "z"*100000 + "\ue007")

How to use onkeyup in javascript to add text to a div that isn't a textbox?

Let me start off saying that I am new to javascript.
I am trying to change a div's content to whatever letter I type in. So if I press "p" anywhere on the page, the div text will add that letter.
For example:
<html>
<head>
<script>
document.getElementById("change").onkeyup = function() {myFunction()};
function myfunction(){
}
</script>
</head>
<body>
<div id=change>p</div>
</body>
</html>
The function is where I am stuck.
I have seen a lot of examples involving typing in a textbox but none without one. If someone could guide me in the right direction, I would be very grateful.
Why does your code not work?
You can't use the keyup event on the <div> element as you have tried to do, because JavaScript will never fire it as the div is never focused. Elements have to be focused to receive keypress events, otherwise how would the user know where their keyboard was going to type to.
What can we do about that?
One element that always "has focus" is the <body> of the webpage (unless of course, you are using a different area of your web browser, such as bookmarking a site, navigating with the URL bar, etc).
So, we can detect the event on the body of the page, and then change the content of the div accordingly. We can detect the event using document.body.onkeyup = function(event), and then get change the div content using document.getElementById("change").innerHTML, which targets that div by it's ID, and then sets it's HTML value to something new.
However, JavaScript will only send back the code of the key that was pressed (it's internal representation of the key), not the character which the key represents - (this is actually useful if you are trying to detect if a key like backspace or ctrl has been pressed). We can get this value from the event using event.keyCode.
Thus, we will have to transform that into a string, which is the final piece of our code : String.fromCharCode(event.keyCode). This transforms a character code into a string.
All together, we can update the value of the div in response to a key press.
Working Example
document.body.onkeyup = function(event) {
document.getElementById("change").innerHTML = String.fromCharCode(event.keyCode);
}
<div id="change">p</div>
Notes
You can use onkeypress rather that onkeyup if you want to detect the case of letters;
You can use += rather than = if you want to append what you have typed now to what is already in the div;
If you want to just use a div as a place where you can type, check out contenteditable;
If you want a list of keycodes that do not map to a string value, check out this list.
If you want to add the letters as you press you can add use +=. Also onkeypress is case sensitive while onkeyup will give you capital letters.
document.body.onkeypress = function(event) {
document.getElementById("change").innerHTML += String.fromCharCode(event.keyCode);
}
<div id="change">p</div>

Simple .on('keydown') jQuery event not responding until next key is pressed

I'm making a page for a friend and I have a hidden text field and when the user types the text is transposed into a div so that it looks like they're typing on the screen rather than in an input field.
Here is a link to the page: http://merkd.com/godis.php
Here is the function that I use to respond to the key strokes:
$('#hiddenInput').keydown(function() {
var input = $('#hiddenInput').val();
var html = '<div style="float: left;">'+input+'</div><div id="cursor">|</div>';
$('#typingArea').html(html);
});
The text-field is visible right now so that you can see the problem. When text is entered or deleted, it doesn't respond until the next keypress. So if I type a single letter, nothing shows up until I type the next letter.
I looked at the jQuery .on() documentation but I couldn't find anything on this. Any help is much appreciated.
P.S. I know it should be in a separate question, but is there an easy way to make a text-field always in focus? I want to make it so that no matter where the user clicks or whatever, if they type, the text will still show up.
Use .keyup() event because when you first press (keydown), the letter is never typed so the var html is getting previous value. For second part you can bind keypress event in document to focus your input field.

How to simulate click on <input type="image" />?

when we submit a form using this type of input, the coordinates (x,y) are appended to the result.
it works if I dynamically create 2 hidden inputs, but I wanted something different.
Event or MouseEvent would be great, but I couldn't make it work
here's my current code: (it works fine)
var input = document.createElement("input");
input.type = "hidden";
input.name = "x";
input.value = posx;
my_form.appendChild(input);
input = input.cloneNode(false);
input.name = "y";
input.value = posy;
my_form.appendChild(input);
I'll give you an example of situation
Let's imagine that near to the image form element there is a plain text that says: Click in the image below in any position greater than 20 and lesser than 60
A normal person would read this and click normally.
But I need to, as a robot without hands, simulate the same click event
Without fully understanding what you are trying to do here (your question is a little vague, IMO), I have to ask this: Have you ever considered using jQuery or another javascript library/framework? I understand sometimes, for very simple sites, it's overkill. But, it might be worth it to relieve the headache of figuring this stuff out on your own.
From what I can understand, you are using an "image" form element to submit a form and you want to simulate a click on the image element to retrieve the x/y coordinates of something. I could be wrong. Could you be more explicit in your details?
I'll see if I can show you how to do it in jQuery when I know more about your problem.
I can't tell what you're trying to append the result to. The values in the form? This is automatic and requires no code (they come across and x and y, or elementname.x and elementname.y).
edited after comment:
You can avoid the node insert event by not making the elements at that time; ie add x and y to the form. Then on the event you can simply set their value. There are certainly different events you could bind this too, and I don't know your situation, but I made an example that uses an onClick event attached to the body of the page itself. You may want, instead, to bind specific onClick events to different clickable items and insert your own locations for them but in my case I submitted the location of the mouse on the page. If that's not helpful, make a comment about why and I'll see if I can mod it again.

Categories