| Class | WWW::Mechanize::Form |
| In: |
lib/mechanize/form.rb
|
| Parent: | GlobalForm |
This class encapsulates a form parsed out of an HTML page. Each type of input fields available in a form can be accessed through this object. See GlobalForm for more methods.
Find a form and print out its fields
form = page.forms.first # => WWW::Mechanize::Form
form.fields.each { |f| puts f.name }
Set the input field ‘name’ to "Aaron"
form['name'] = 'Aaron' puts form['name']
| node | [R] | |
| page | [R] |
# File lib/mechanize/form.rb, line 222
222: def initialize(node, mech=nil, page=nil)
223: super(node, node)
224: @page = page
225: @mech = mech
226: end
Set the value of the first input field with the name passed in
Set the value in the input field ‘name’ to "Aaron"
form['name'] = 'Aaron'
# File lib/mechanize/form.rb, line 286
286: def []=(field_name, value)
287: f = field(field_name)
288: if f.nil?
289: add_field!(field_name, value)
290: else
291: f.value = value
292: end
293: end
# File lib/mechanize/form.rb, line 235
235: def has_value?(value)
236: ! fields.find { |f| f.value.eql? value }.nil?
237: end
Treat form fields like accessors.
# File lib/mechanize/form.rb, line 296
296: def method_missing(id,*args)
297: method = id.to_s.gsub(/=$/, '')
298: if field(method)
299: return field(method).value if args.empty?
300: return field(method).value = args[0]
301: end
302: super
303: end
This method sets multiple fields on the form. It takes a list of field name, value pairs. If there is more than one field found with the same name, this method will set the first one found. If you want to set the value of a duplicate field, use a value which is an Array with the second value of the array as the index in to the form. The index is zero based. For example, to set the second field named ‘foo’, you could do the following:
form.set_fields( :foo => ['bar', 1] )
# File lib/mechanize/form.rb, line 261
261: def set_fields(fields = {})
262: fields.each do |k,v|
263: value = nil
264: index = 0
265: v.each do |val|
266: index = val.to_i unless value.nil?
267: value = val if value.nil?
268: end
269: self.fields.name(k.to_s).[](index).value = value
270: end
271: end