Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium Webdriver enter multiline text in form without submitting it

I have a multiline text and when I am simply putting the whole text into a form using sendKeys, the form gets submitted on each line break.

I tried replacing the newline with carriage return this way:

String myText="Some Multiline Text....";
myText=myText.replace("\n","\13");

This simply removed the newlines and I could not see the newline in output text.

Also below did not work(it also submits form at line breaks):

String myText="Some Multiline Text....";
myText=myText.replace("\n","\r");

So how do I go about with newlines in sendkeys without submitting the form?

like image 407
rahulserver Avatar asked Nov 18 '15 15:11

rahulserver


People also ask

Can we enter text without using SendKeys () in Selenium?

We can input text in the text box without the method sendKeys with thehelp of the JavaScript Executor. Selenium executes JavaScript commands with the help of the executeScript method. The JavaScript command to be run is passed as parameter to the method.

How do you write text in a new line inside a text area?

By default, whenever we press “enter” or “shift+enter” it creates a new line in the text area.

What is xOffset and yOffset in Selenium?

Both xOffset and yOffset represent the relative pixel distance (integer) with which to scroll. For xOffset , positive value means to scroll right, and negative value means to scroll left. For yOffset , positive value means to scroll downward, and negative value means to scroll upward.


2 Answers

This is not a Selenium issue, pressing enter in a text field often submits the form. Usually you can bypass it by using Shift+Enter to insert a new line. Try this:

String myText = "first line\nsecond line";
myText = myText.replace("\n", Keys.chord(Keys.SHIFT, Keys.ENTER));
myElement.sendKeys(myText);
like image 135
Tamas Hegedus Avatar answered Oct 22 '22 04:10

Tamas Hegedus


What worked for me using python 3 was make use of ActionChain as Tamas said and @Arount posted on Python and Selenium - Avoid submit form when send_keys() with newline

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Chrome()
driver.get('http://foo.bar')

inputtext = 'foo\nbar'
elem = driver.find_element_by_tag_name('div')
for part in inputtext.split('\n'):
    elem.send_keys(part)
    ActionChains(driver).key_down(Keys.SHIFT).key_down(Keys.ENTER).key_up(Keys.SHIFT).key_up(Keys.ENTER).perform()
like image 29
Leonardo Wolter Avatar answered Oct 22 '22 02:10

Leonardo Wolter