Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

javascript - How to edit HTML (remove readonly) and type in input box using JS Executor?

This is the piece of HTML code on the particular page:

<input size="24" autocomplete="off" id="sch-555-et" 
name="./schimage" class="x-form-text x-form-field 
x-trigger-noedit" readonly="" style="width: 263px;" type="text">

It allows to browse image and refrains user to type in. I am told to skip the browsing part as it is error-prone also it isn't part of manual or automation tests.

I know how to type using JS Executor (https://www.softwaretestingmaterial.com/javascriptexecutor-selenium-webdriver/) but don't know how to edit HTML and then type.

Edit: I don't know how my question is duplicate of Disable readonly to text box onclicking the button

Anyways I tried:

public JavascriptExecutor executeJS() {
    JavascriptExecutor jsexec = (JavascriptExecutor).driver;
    return jsexec;
}

executeJS().executeScript("document.getElementById('sch-555-et').removeAttribute('readonly')");

but it didn't remove "readonly" and element remain un-editable.

I tried to automate this page http://jsfiddle.net/343Rb/ also, and here it is giving error

  1. Cannot set property 'readOnly' of null when trying to set value of readonly as null.
  2. Cannot read property 'removeAttribute' of null when trying to remove readonly.

I am using Windows, Java, Selenium, Maven and TestNg

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can edit the value property to simulate typing. This will work even if the readonly attribute is present. But if you do want to remove the attribute, use Element.removeAttribute.

var el = document.getElementById('sch-555-et');

// Note: you can edit the value even if the readonly attribute is present.
el.removeAttribute('readonly');

el.value = 'Edited';
<input size="24" autocomplete="off" id="sch-555-et" 
name="./schimage" class="x-form-text x-form-field 
x-trigger-noedit" readonly="" style="width: 263px;" type="text">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...