I am having an issue clicking on a specific checkbox where it should check all the other check-boxes below it (root parameter). It used to work when I used this code on the element:
arguments[0].click();
I have tried to use normal click
method but it does not work, I also tried to use:
("document.getElementById('" + checkBoxID + "').checked=true");
("document.getElementById('" + checkBoxID + "').onchange();")
What I have found is when I'm triggering the click by JS
, the response is different than if i'd click on the checkbox manually . It is worth mentioning that clicking manually on the checkbox does trigger the event correctly and the other checkbox's below the main checkbox are checked as-well. Are there any other possible ways to trigger the onchange
event? I tried to force onchange
with this command:
document.getElementById("test").onchange()
Thanks in advance.
As you are saying selenium click()
does not as work expected, you should try using JavascriptExecutor
to trigger MouseEvents
as below :-
WebElement el = driver.findElement(By.id("checkboxId"));
JavascriptExecutor executor = (JavascriptExecutor)driver
executor.executeScript("function triggerMouseEvent (node, eventType) {"
+ "var clickEvent = document.createEvent ('MouseEvents');"
+ "clickEvent.initEvent (eventType, true, true);"
+ "node.dispatchEvent (clickEvent);"
+ "}triggerMouseEvent (arguments[0], 'mouseover');"
+ "triggerMouseEvent (arguments[0], 'mousedown');"
+ "triggerMouseEvent (arguments[0], 'mouseup');"
+ "triggerMouseEvent (arguments[0], 'click');", el);
Edited1 :- If you want to make you checkbox visible using executeScript
and want to perform using selenium
click()
, try as below :-
el = (WebElement)executor.executeScript("arguments[0].style.display = 'block';return arguments[0];", el);
el.click();
Edited2 :- I think you are not pointing correct check box to click as I seeing in your provided HTML checkbox id may be dynamically generated, you should implement WebDriverWait
ti wait until checkbox visibile as below :-
JavascriptExecutor executor = (JavascriptExecutor)driver
WebElement el = (WebElement)executor.executeScript("return document.getElementById('flattendListproductLinesTree|1@innerVO@isSelected')");
WebDriverWait wait = new WebDriverWait(driver, 10);
el = wait.until(ExpectedConditions.visibilityOf(el)));
el.click();
Hope it helps...:)
function simulateClick() {
var event = new MouseEvent('click', { 'view': window, 'bubbles': true, 'cancelable': true }); //creates a mouse event
var cb = document.getElementById('checkbox'); var canceled = !cb.dispatchEvent(event); //fires the event.
}
Example from here .To run the javascript code using selenium see the next answer...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.