Skip to content

Instantly share code, notes, and snippets.

@gomo
Last active July 5, 2017 07:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gomo/31559996f597e12b6e04e3d8a0bf1c98 to your computer and use it in GitHub Desktop.
Save gomo/31559996f597e12b6e04e3d8a0bf1c98 to your computer and use it in GitHub Desktop.
How to check checkboxes by values using javascript selenium.

Both getAttribute and isSelected are asynchronous methods, so my solution has become such complicated. Does anyone know a simpler solution?

import webdriver from 'selenium-webdriver';
const Promise = webdriver.promise;//Promise.map not supported in native Promise.
const values = ['1', '3']
driver.findElements(By.css('.checkbox[name=foobar]'))
// make objects like {elem: element, value: '1'}
.then(elems => Promise.map(
elems,
elem => elem.getAttribute('value').then(value => ({elem: elem, value: value}))
))
// add checked status to adove objects. {elem: element, value: '1', isSelected: false}
.then(composits => Promise.map(
composits,
composit => composit.elem.isSelected().then(isSelected => ({elem: composit.elem, value: composit.value, isSelected: isSelected}))
))
// filter to unchecked and specified values
.then(composits => composits.filter(composit => !composit.isSelected && action.values.indexOf(composit.value) >= 0))
// click
.then(composits => Promise.map(
composits,
composit => composit.elem.click()
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment