How to validate Check box if xpaths are same in case of selected and unselected

╄→гoц情女王★ 提交于 2021-02-05 07:18:06

问题


M unable to validate checkbox, if it's selected or not because both the HTML are same

I tried isSelected(), but it's not working

Below is the HTML code for both selected and unselected

1) Selected

<label class="c-account-access-panel__checkbox " for="23336" data-js-checkbox-label="">
<input id="23336" class="c-account-access-panel__checkbox-input" type="checkbox" 
data-label-for-value-missing="Please select at least one account from the options below" data-form-field-validation-on-grid="" 
required="" checked="" data-js-checkbox="" value="DE29973399" name="payer"/>
<div class="c-account-access-panel__checkbox-symbol"/>

2) Unselected

<label class="c-account-access-panel__checkbox " for="23336" data-js-checkbox-label="">
<input id="23336" class="c-account-access-panel__checkbox-input" type="checkbox" 
data-label-for-value-missing="Please select at least one account from the options below" data-form-field-validation-on-grid="" 
required="" checked="" data-js-checkbox="" value="DE29973399" name="payer"/>
<div class="c-account-access-panel__checkbox-symbol"/>

Thanks in advance!


回答1:


As per the Java Docs isSelected() method determines whether the element is selected or not. This operation only applies to <input> elements such as checkboxes, options within a <select> tag and radio buttons.

To validate if the desired checkbox is selected or not you can use the following code block:

boolean checkboxSelected = driver.findElement(By.xpath("//input[@class='c-account-access-panel__checkbox-input' and @name='payer']")).isSelected();



回答2:


If isSelected() is not working for you. Then , you can use JavascriptExecutor to do your task. Following JS statements shall let you know the state of target checkbox.

document.getElementById("23336").click();
document.getElementById("23336").checked;

The checked method returns true or false depending on the checkbox state.




回答3:


You can validate using getAttributemethod.

First select the webElement using any of the unique locator,

 WebElement checkbox=driver.findElement(By.xpath(".//input[@type='checkbox']"));

If the checkbox is selected, then checkbox.getAttribute("checked")will give the result as true else, it will give the result as null. So, you can add the condition using checkbox.getAttribute("checked")




回答4:


Use xpath expression like: (//div [@id='23336')[1] or (//div [@id='23336')[2] to make them into unique element then do .isselected ()



来源:https://stackoverflow.com/questions/50616459/how-to-validate-check-box-if-xpaths-are-same-in-case-of-selected-and-unselected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!