简体   繁体   中英

Best way to submit a value with a button in a wizard form

I've been trying to create a wizard form that is basically a series of Yes or No questions. There's also a couple pages in the form where the user will have to select multiple options before continuing.

Right now all the object parameters are mostly booleans but all the wizard examples I've seen involve basic forms (text_fields, check_box's, etc.).

I figured I might be able to do something like this:

<div class="button1">
    <%= f.hidden_field :newsletter, value: "1" %>
    <%= f.submit "Yes" %>
</div>

<div class="button2">
    <%= f.hidden_field :newsletter, value: "0" %>
    <%= f.submit "No" %>
</div>

But it doesn't seem to be saving the value. I'm using the wicked gem for the wizard and am following this RailsCast tutorial

Note: Normal fields like text_fields save, just not these button booleans.

Both those buttons, and the hidden fields, are all in the same form. So, either button will submit the form, and when the form submits it will gather the values of all the fields into params.

What you can do is to make the buttons themselves into an input, sending through a param. This is done with "name" and "value" attributes, like any other attribute:

<input type="submit" value="foo" name="bar" />
<input type="submit" value="chunky" name="bacon" />

Now if you submit with the first button you will get :bar => "foo" in params and if you submit with the second you'll get :bacon => "chunky" .

The conventional name is "commit". When you use a rails submit_tag, it will set "name" to "commit" and it will set "value" to the text of the button. So, you should see :commit => "Yes" or :commit => "No" in params, and change your logic accordingly.

It's better to use jQuery to trigger an event and add the hidden input accordingly

<div class="button1">
  <%= f.submit "Yes", class: "wizard-btn" %>
</div>

<div class="button2">
  <%= f.submit "No", class: "wizard-btn" %>
</div>
... ...

sample coffeescript code would be like below:

jQuery ->
  $(".wizard-btn").on "click", (e) ->
    e.preventDefault()
    thisForm = $(".wizard-form")
    hideDiv = "<input type=\"hidden\" name=\"newsletter\" />"
    if $(this).val() == "Yes"
      thisForm.append $(hideDiv).val("1")
    else if $(this).val() == "No"
      thisForm.append $(hideDiv).val("0")
    thisForm.get(0).submit()

where I assume your form has class named: wizard-form

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM