1. Computing

Checkboxes and Radiobuttons

By

Checkboxes and radio buttons are "clicked." As such, the method to interact with them is click, or the more specific check and uncheck. The difference is that if you call click multiple times on the same check box or radio button, it will alternately check and uncheck the the box, while check and uncheck do just as they sound, check and uncheck the box. And obviously, Mechanize honors the radio button behavior, checking one will uncheck the others.

To query the status of any check box or radio button, you can use the checked method. It will return true if the button has been checked.


#!/usr/bin/env ruby
require 'rubygems'
require 'mechanize'

agent = Mechanize.new
page = agent.get('http://www.reddit.com/login')
form = page.form_with(:action => %r{post/login})

# Set the username and password
form.user = 'fake_user'
form.passwd = 'fake_password'

# The "remember me" checkbox is called "rem"
puts %Q{"remember me" is #{form.checkbox_with('rem').checked ? "" : "un"}checked}

form.checkbox_with('rem').check
form.submit
  1. About.com
  2. Computing
  3. Ruby
  4. Tutorials
  5. The Mechanize 2.0 Handbook
  6. Checkboxes and Radiobuttons

©2014 About.com. All rights reserved.