How to clear the attribute value of an element using selenium webdriver - selenium

I have an element, which is kendo numeric textbox. It has values as well, I can get the value by using this code snippet driver.findElement(By.xpath("xpathlocator_value")).getAttribute("value"); but i want to clear the value and i want to update this element with another value. I tried
both the ways like using clear() and alsosendkeys(keys.control +"a",keys.delete)
but its not working.
The html code is
<form id="cashbookForm" class="form">
<div class="widget">
<table class="sTable taskWidget" width="100%" cellspacing="0" cellpadding="0">
<thead>
<tbody>
<tr data-bind="css:ExpenseID()==0?'non-printable':'',click:$root.CloseEditable">
<tr data-bind="css:ExpenseID()==0?'non-printable':''">
<td data-bind="text:Order">2</td>
<td>
<td>
<td>
<td>
<td>
<div style="float: right;">
<span class="k-widget k-numerictextbox noform required" style="text-align: right;">
<span class="k-numeric-wrap k-state-default">
<input class="k-formatted-value noform required k-input" type="text" style="text-align: right; display: inline;" tabindex="0" readonly="readonly">
<input class="noform required k-input" type="text" data-bind="kendoNumericTextBox: { value: Ca_TotalAmount, min: 0,format: '#.00'},uniqueName:true" style="text-align: right; display: none;" data-role="numerictextbox" role="spinbutton" tabindex="0" aria-valuemin="0" aria-valuenow="251.44" name="ko_unique_4">
<span class="k-select">
</span>
</span>
</div>
</td>
<td> </td>
<td class="removeOnPrint">
</tr>
<tr class="removeOnPrint">
Here the numeric textbox present at
<input class="k-formatted-value noform required k-input" type="text" style="text-align: right; display: inline;" tabindex="0" readonly="readonly">

You can use JavascriptExecutor to achieve the goal.
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("window.document.getElementById("elementID").setAttribute('value', ' ')");
or
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("window.document.getElementById("elementID").value = ' '");
If you want to use xPath:
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("document.evaluate('xpath_locator', document, null, 9, null).singleNodeValue.value = ' '");

This is a pretty old question, but I'm posting the answer here in case someone finds it useful. If you're using selenium and you want to remove attribute and not clear it, then here's what works:
public static void javascriptRemoveAttribute(WebElement element, WebDriver driver) {
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].removeAttribute('required');", element);
}
It is similar to the first answer but they key is removeAttribute. ExecuteScript basically expects an array of elements. So you pass the element when needs to be modified and then remove its attribute.

Using this function you can change the value of the element:
public void clearElementValueByJS(WebElement element, WebDriver driver, Stringvalue) {
try {
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("arguments[0].value='" + value + "'", element);
} catch (Exception e) {
e.printStackTrace();
}
}
OR you can change the inner html value of the element:
public void setInnerHTMLValue(WebElement element, String value) {
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("return arguments[0].innerText ='" + value + "'", element);
}

Related

xpath with Multiple condition in Selenium

Wants to locate element with multiple condition on particular row,
I want to Click on div which contains ng-click="condition001" which has parent link contains Auto-001
So query become like : Select element xpath("//div[contains(#ng-click,'condition001')]") where Link("Auto-001")
<tr ng-repeat="(abc, xyz)" ng-show="data.length > 0">
<td class="x001">
<div class="x002">
<a class="x003" href="#">Auto-001</a>
</div>
</td>
<td class="x004">
<div class="x005">
<div class="x006">
<div class="x007" ng-click="condition001" tabindex="0">
<i class="x008"></i>
</div>
</div>
</div>
</td>
</tr>
Please suggest relevant xpath code which can work for above criteria,
To click on the WebElement identified through xpath as ("//div[contains(#ng-click,'condition001')]") where it has partialLinkText as ("Auto-001") you can use the following line of Java code :
WebElement myElem = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[#class='x003' and contains(.,'Auto-001')]//following::td[1]//div[#class='x007' and #ng-click='condition001']")));

Not able to find the elements under nobr tag

Not able to find the element with input tag. Need to find the element in the input tag. eclipse could catch the element till nobr and not further.
input id="ServiceFromDate" class="inactvDtTmTxt" name="$PHCClaimSearch$pServiceFromDate" data-ctl="["DatePicker"]" data-formatting="yes" value="05/02/2017" data-value="5/2/2017" style="padding-right:17px;width:11.719em;" validationtype="date" data-change="[["refresh", ["thisSection","", "", "&=", "", ",",":event","","HCClaimSearch"]]]" data-display-value="05/02/2017" type="text"/>
//table[contains(#role,'presentation')][contains(#id,'pyActionArea')]//table[1]//table[contains(#role,'presentation')][contains(#section_index,'1')]//tbody//tr[2]//td[1]//following::nobr[1]//following::span[#id='$PHCClaimSearch$pServiceFromDateSpan']/input
driver.findElement(By.xpath("//input[#id='ServiceFromDate']")).sendKeys("04242015")
<table id="" role="presentation" section_index="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<tr>
<td class="dataLabelWrite" style="height:24px;width:143px;">
<td class="dataValueWrite" style="height:24px;width:190px;">
<nobr>
<ins id="pega-calendar" style="display: none;" data-calendar="{"img":"webwb/pzspacercal_12860256145.gif!!.gif","locale":[["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58","59"],0,"M/d/yyyy","M/d/yyyy h:mm a","Today",["January","February","March","April","May","June","July","August","September","October","November","December"],["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],["AM","PM"],"Apply","Close"]}"/>
<script> var positionDatePickerIcn = function(control){ /* BUG-47098 - Following block filters out IE8(both quirks and standards modes) and IE9 (standards mode) */ var addMarginFlag = true; if(document.documentMode && navigator.userAgent.indexOf("Trident/4") > -1){ //IE8: skip for both standards and quirks mode addMarginFlag = false; } else if(document.documentMode && document.documentMode >= 9 && navigator.userAgent.indexOf("Trident/5") > -1){ //IE9: skip for standards mode addMarginFlag = false; } if (addMarginFlag) { var icnEle = control.lastChild; if(icnEle.tagName.toLowerCase() == 'img'){ icnEle.style.marginTop = '0px'; } } }; </script>
<span id="$PHCClaimSearch$pServiceFromDateSpan" role="group" aria-label="Service From Date : " data-calendar="{"d":[0,0],"l":0}" style="display:inline-block; width:inherit;" onmouseover="pega.c.DatePicker.dtTmHvr(event);">
<input id="ServiceFromDate" class="inactvDtTmTxt" name="$PHCClaimSearch$pServiceFromDate" data-ctl="["DatePicker"]" data-formatting="yes" value="05/02/2017" data-value="5/2/2017" style="padding-right:17px;width:11.719em;" validationtype="date" data-change="[["refresh", ["thisSection","", "", "&=", "", ",",":event","","HCClaimSearch"]]]" data-display-value="05/02/2017" type="text"/>
<img class="inactvIcon" src="webwb/pzspacer_11792674401.gif!!.gif" data-ctl="["DatePicker"]" style="cursor:pointer;"/>
</span>
</nobr>
</td>
<td class="dataLabelWrite" style="height:24px;width:125px;">
<td class="dataValueWrite" style="height:24px;width:190px;">
<td class="dataLabelWrite" style="height:24px;width:101px;">
</tr>
</tbody>
</table>
The problem is with the HTML, at least as you've pasted here.
there are a number of places inside that tag that have double-quoted text inside of double-quoted text. e.g. the input element has the following attribute:
data-ctl="["DatePicker"]"
Other attributes I found with this problem: data-calendar, data-change
Once I corrected all of the places that this is a problem with outer single quotes, I was able to find the input using your Xpath from the Chrome developer tools
data-ctl='["DatePicker"]'
As you mentioned, you could catch the element till <nobr> tag and not further that is because the <ins> tag is having style="display: none;", so will use JavascriptExecutor to change the attribute and then send the text as follows :
((JavascriptExecutor)driver).executeScript("document.getElementById('pega-calendar').style.display='block';");
driver.findElement(By.xpath("//input[#id='ServiceFromDate']")).sendKeys("04242015");

how to write xpath to click on the "add" button

<tr>
<td id="Action1_Td_Add">
<a id="Action1_But_Add" class="btn cus-action-btn-add btn-xs" href="javascript:__doPostBack('Action1$But_Add','')" alternatetext="" title="Add" onclick="return Add_Click();">
<i class="fa fa-plus"/>
</a>
</td>
</tr>
I have tried the using the css selector.
driver.findElement(By.cssSelector("a[title='Add']")).click();
but the action was not preformed.
It's not a problem with xpath. Use Java Script click instead of click. Like this, Hope this will help.
WebElement element = driver.findElement(By.cssSelector("a[title='Add']"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);

Selenium Webdriver - (Java) - Click a button with dynamic ID

1) I have a dialog on my web page having 2 buttons, Yes & No.
2) IDs of these buttons are dynamicaly changing every time.
3) How to handle this situation and click on Yes button?
4) Both buttons, Yes & No, have same classname 1.e. rwInnerSpan
5) Here is the Xpath for Yes button
(.//*[#id='confirm1381468352443_content']/div/div[2]/a[1]/span/span)
the part 1381468352443 in xpath is dynamically changing.
Below is the source code of page
`
<tr class="rwTitleRow">
<tr class="rwContentRow">
<td class="rwCorner rwBodyLeft"> </td>
<td class="rwWindowContent" valign="top">
<iframe frameborder="0" name="confirm1381468352443" src="javascript:'<html></html>';" style="width: 100%; height: 100%; border: 0px none; display: none;" tabindex="0">
<div id="confirm1381468352443_content">
<div class="rwDialogPopup">
<div class="rwDialogText">
<div>
<a class="rwPopupButton" href="javascript:void(0);" onclick="$find('confirm1381468352443').close(true);" tabindex="-1">
<span class="rwOuterSpan">
<span class="rwInnerSpan">Yes</span>
</span>
</a>
<a class="rwPopupButton" href="javascript:void(0);" onclick="$find('confirm1381468352443').close(false);" tabindex="-1">
<span class="rwOuterSpan">
<span class="rwInnerSpan">No</span>
</span>
</a>`
Thanks in Advance !!
You can directly check for the text in your Xpath:
driver.findElements(By.xpath("//a[#class='rwPopupButton']/span/span[contains(text(), 'Yes')]"))
There is a way to locate objects using partial link text, so you can try this:
driver.findElement(By.partialLinkText("Yes")).click();
Plain By.linkText may not work because of additional spaces or characters in the link.
You can click on the button based on the Text. Following method will give you a webelement based on the class locator and text.
WebElement getElementBasedOnClassAndText(String classLocator, String text){
List<WebElement> elements = driver.findElements(By.className(classLocator))
for(WebElement element : elements){
if(element.getText().contentEquals(text)){
return element
}
}
Assert.fail("Unable to find any element with the said Text")
}
Once you get the element you can take any action on it.
Since it is dynamic I would look for the changed name:
//Find the dynamicly created ID
String dynamicID = driver.findElement(By
.xpath("//iframe[contains(#name,'confirm')]")
.getAttribute("name");
//Use that ID to find the Yes option
driver.findElement(By
.xpath("//*[#id='"+dynamicID +"_content']/div/div[2]/a[1]/span/span")
.click();

Not able to click the button after entering value in textarea Options

code is used is:
WebElement desc=driver.findElementByXPath(".//*[#label='Description']");
desc.sendKeys("testing");
desc.sendKeys(Keys.ENTER);
List<WebElement> button=driver.findElementsByXPath("(//div[#id='sv'])[1]");
for (WebElement buttonname : button)
{
System.out.println("buttonname: "+buttonname.getAttribute("id"));
String but = buttonname.getAttribute("id");
driver.findElementById(but).click();
}
Below is the html code of that textarea and button .
<td>
<textarea id="1992800000" label="Description" ft="12" mand="false"class="ic" maxlength="120" cols="13" rows="2"/>
</td>
......
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 40px; ">
<td class="pdl">
<div class="tbut" onclick="ir('Tas','tas','')" id="sv">Save</div>
</td>
Your XPath can only select one element, so there is no need to create a list and iterate through it.
Try something more like:
WebElement desc=driver.findElementByXPath("//*[#label='Description']");
desc.sendKeys("testing");
WebElement button=driver.findElementsByXPath("(//div[#id='sv'])[1]");
button.click();