JiaHao Wang
JiaHao Wang

Reputation: 101

Javascript to input value into textbox instead of sendKeys() in Python

I cant use send_Keys() method to input values in the current website im working on. So im trying to use javascript to input values.

i tried click() and clear() together with send_keys() before i decided to use javascript but to my disappointment, it didnt work.

i use the javascript code to input value below

driver.execute_script("document.getElementById('CustCd').setAttribute('value', 'J590')")

and it worked.

But currently my code is inside a loop and the value changes, how can i replace J590 with a variable that gets the value?

Here is the code that i tried

ccr_No = XLUtlis.readData(path, 'ccr', r, 1)
driver.execute_script("document.getElementById('CCRNo').value=ccr_No")

I know its wrong, any help would be appreciated. My Javascript is weak.

Just some side note if anybody would be able to solve my send_keys() error. The function only takes in the first character that i send. For example, send_keys("J590") gives J, send_keys("J590-TE21") gives J-

Upvotes: 0

Views: 1392

Answers (3)

undetected Selenium
undetected Selenium

Reputation: 193108

Using Javascript to input the values of a variable you can use the following solution:

ccr_No = XLUtlis.readData(path, 'ccr', r, 1)
# ccr_No = J590
driver.execute_script("document.getElementById('CCRNo').value='" + ccr_No + "';")

An example, to input the values of a variable within Search Box of Google Home Page:

  • Code Block:

    driver.get("https://www.google.com/")
    value = 'J590'
    driver.execute_script("document.getElementsByName('q')[0].value='" + value + "';")
    
  • Browser Snapshot:

variable

You can find a relevant discussion in Selenium : How to send variable character strings through executeScript()

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074485

First, the correct way to set the current value of an input is to assign to the value property. There is no attribute for the inputs current value (the value attribute is the input's default value, more here).

The rest is a special case of a general-purpose question: "How do I output a Python variable's value into JavaScript code?"

If the string you're outputting doesn't contain quotes or backslashes, you may get away with using a format string and outputting the value in quotes as Guy shows. (JavaScript has two kinds of quotes, ' and "; you only need to escape the kind you use around the value.) Those kinds of assumptions tend to break down, though; as soon as the string is Hi, I'm Joe that approach breaks.

In the general case, to ensure proper escaping and that all values are written correctly, you can use JSON:

import json
value = 'J590'
driver.execute_script(f"document.getElementById('CustCd').value = {json.dumps(value)};")

That outputs:

document.getElementById('CustCd').value = "J590";

Live Example

That way, you don't have to worry about quoting and escaping, it's all handled for you since valid JSON is valid JavaScript (thanks to a recent JavaScript specification fix; prior to that there was an edge case incompatibility that people almost never ran into).

It's also useful for numbers, or more complex things you might want to pass to hte JavaScript code. For instance:

import json

class Example:
    foo = ""
    bar = 0

    def __init__(self, foo, bar):
        self.foo = foo
        self.bar = bar

value = Example("I'm a string with \"quotes\" in it.", 42)
print(f"const obj = {json.dumps(value.__dict__)};")
num = 42
print(f"const num = {json.dumps(num)};")

That outputs:

const obj = {"foo": "I'm a string with \"quotes\" in it.", "bar": 42};
const num = 42;

obj ends up being an object, because the initializer is a valid JavaScript object literal containing the data from the Example object. Similarly, num is a valid JavaScript number.

Live Example

Upvotes: 1

Guy
Guy

Reputation: 50864

You need to insert the variable as variable, not literal

value = 'J590'
driver.execute_script(f"document.getElementById('CustCd').setAttribute('value', '{value}')")

Upvotes: 1

Related Questions