Joe
Joe

Reputation: 293

How to get value of a hidden element? (Watir)

just wondering, how can I get the value of a hidden element using watir? This is the element:

<input type="hidden" value="randomstringhere" id="elementid" name="elementname" />

And this is my code atm:

require "rubygems"
require "watir-webdriver"
$browser = Watir::Browser.new :ff
$browser.goto("http://www.site.com")
$grabelement = $browser.hiddens(:id, "elementid")
$blah = $grabelement.attribute_value("value")
puts $blah

This gets stuck at the last line, where it returns

code.rb:6:in `<main>': undefined method `attribute_value' for #<Watir::HiddenCollection:0x8818adc> (NoMethodError)

Sorry for the basic question, I've had a search and couldn't find anything.

Thanks in advance!

Upvotes: 2

Views: 4773

Answers (1)

Justin Ko
Justin Ko

Reputation: 46846

Problem

Your code is quite close. The problem is the line:

$grabelement = $browser.hiddens(:id, "elementid")

This line says to get a collection (ie all) of hidden elements that have id "elementid". As the error message says, the collection does not have the attribute_value method. Only elements (ie the objects in the collection) have the method.

Solution (assuming single hidden with matching id)

Assuming that there is only one, you should just get the first match using the hidden instead of hiddens (ie drop the s):

$grabelement = $browser.hidden(:id, "elementid")
$blah = $grabelement.value
puts $blah
#=> "randomstringhere"

Note that for the value attribute, you can just do .value instead of .attribute_value('value').

Solution (if there are multiple hiddens with matching id)

If there actually are multiple, then you can iterate over the collection or just get the first, etc:

#Iterate over each hidden that matches
browser.hiddens(:id, "elementid").each{ |hidden| puts hidden.value }

#Get just the first hidden in the collection
browser.hiddens(:id, "elementid").first.value

Upvotes: 7

Related Questions