1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Buttons and Submitting Forms


Buttons primarily exist to submit forms. They may be there for different reasons, however, that will require Javascript and Mechanize doesn't do Javascript. The only thing that complicates matters is the possible existence of multiple submit buttons.

Typically, in forms with a single submit button, you could simply say form.submit. This is by far the most common way of submitting forms. It will build the POST or GET query, perform the query and return a new Mechanize::Page object.

If there are multiple submit buttons, you can "click" on a specific button by passing that button as the first argument to the submit method. For example, if there is a button with the text "Google Search" as well as a button with the text "I'm Feeling Lucky", you could do the following.

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

agent = Mechanize.new
page = agent.get('http://www.google.com/')
form = page.form_with(:action => '/search')

# Set the 'q' field like this
form.q = "Ruby Programming Language"

# I'm feeling lucky!
page2 = form.submit( form.button_with(:value => "I'm Feeling Lucky") )
puts page2.title
  1. About.com
  2. Technology
  3. Ruby
  4. Tutorials
  5. The Mechanize 2.0 Handbook
  6. Buttons and Submitting Forms

©2014 About.com. All rights reserved.