make radiobutton exclusive

master
Kanezoh 2021-06-17 12:04:45 +09:00
parent f36767ad7f
commit fe730164f3
3 changed files with 43 additions and 9 deletions

View File

@ -11,6 +11,9 @@ WebMock.stub(:get, "example.com/check_form").to_return(body:
<input type="text" name="name">
<input type="text" name="email">
<input type="checkbox" id="remember_me" name="remember_me" checked>
<input type="radio" id="contactChoice1" name="contact" value="email">
<input type="radio" id="contactChoice2" name="contact" value="phone">
<input type="radio" id="contactChoice3" name="contact" value="mail">
</form>
</body>
</html>
@ -65,4 +68,33 @@ describe "Mechanize Form test" do
form.request_data.should_not contain("remember_me=")
end
end
context "Form Fields RadioButton" do
radiobuttons = form.radiobuttons
radiobuttons.size.should eq 3
it "returns radiobutton check status" do
radiobuttons.map(&.checked?).should eq [false,false,false]
end
it "can change check status" do
radiobutton = radiobuttons.first
radiobutton.checked?.should eq false
radiobutton.check
radiobutton.checked?.should eq true
radiobutton.uncheck
radiobutton.checked?.should eq false
# #click reverses check status
radiobutton.click
radiobutton.checked?.should eq true
radiobutton.click
radiobutton.checked?.should eq false
end
it "check status is exclusive" do
radiobuttons[0].check
radiobuttons[0].checked.should eq true
radiobuttons[1].checked.should eq false
radiobuttons[1].check
radiobuttons[1].checked.should eq true
radiobuttons[0].checked.should eq false
end
end
end

View File

@ -72,12 +72,15 @@ class MechanizeCr::Form
private def parse
@fields = Array(FormContent::Field).new
@checkboxes = Array(FormContent::CheckBox).new
@radiobuttons = Array(FormContent::RadioButton).new
@node.css("input").not_nil!.each do |html_node|
html_node = html_node.as(Myhtml::Node)
type = (html_node["type"] || "text").downcase
case type
when "checkbox"
@checkboxes << FormContent::CheckBox.new(html_node, self)
when "radio"
@radiobuttons << FormContent::RadioButton.new(html_node, self)
else
@fields << FormContent::Field.new(html_node)
end

View File

@ -2,13 +2,13 @@ class MechanizeCr::FormContent::RadioButton < MechanizeCr::FormContent::Field
property :checked, :form
def initialize(node : Node | Myhtml::Node, form : Form)
@checked = !!node["checked"]
@checked = !!node.fetch("checked", nil)
@form = form
super(node)
end
def check
#uncheck_peers
uncheck_peers
@checked = true
end
@ -52,11 +52,10 @@ class MechanizeCr::FormContent::RadioButton < MechanizeCr::FormContent::Field
#alias eql? == # :nodoc:
#private def uncheck_peers
# @form.radiobuttons_with(:name => name).each do |b|
# next if b.value == value
# b.uncheck
# end
#end
private def uncheck_peers
form.radiobuttons_with(name).try &.each do |b|
next if b.value == value
b.uncheck
end
end
end