Skip to content

Instantly share code, notes, and snippets.

@thijsc
Created November 24, 2011 11:08
Show Gist options
  • Save thijsc/1391107 to your computer and use it in GitHub Desktop.
Save thijsc/1391107 to your computer and use it in GitHub Desktop.
Select item from chosen js select with Capybara and Selenium
def select_from_chosen(item_text, options)
field = find_field(options[:from])
option_value = page.evaluate_script("$(\"##{field[:id]} option:contains('#{item_text}')\").val()")
page.execute_script("$('##{field[:id]}').val('#{option_value}')")
end
@idabmat
Copy link

idabmat commented Feb 12, 2016

For deselecting a specific value :

def deselect_from_chosen(item_text, options)
  field = find_field(options[:from], visible: false)
  page.execute_script("$(\"##{field[:id]} option:contains('#{item_text}')\").removeAttr('selected')")
  page.execute_script("$('##{field[:id]}').trigger('chosen:updated')")
end

@brunzino
Copy link

Here's another deselect function that's more in-line with @thejsc's approach. I like this approach because it triggers the change hook.

def deselect_from_chosen(item_text, options)
  field = find_field(options[:from], visible: false)
  find("##{field[:id]}_chosen ul.chosen-choices li.search-choice", :text => item_text).find("a.search-choice-close").click
end

@westonganger
Copy link

westonganger commented Aug 29, 2016

For anyone whos interested in just selecting whichever option is first without having to know the text

def select_first_from_chosen(from)
  field = find_field(from, visible: false)
  find("##{field[:id]}_chosen").click
  first("##{field[:id]}_chosen ul.chosen-results li").click
end

Use like this: select_first_from_chosen('post[name]')

@JeremiahChurch
Copy link

To guarantee an exact match rather than a partial match aka - find 'OR' and not match 'MORE'
replace
the line

find("##{field[:id]}_chosen ul.chosen-results li", text: item_text).click

with

find("##{field[:id]}_chosen ul.chosen-results li", text: /\A#{Regexp.quote(item_text)}\z/).click

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment