Submitting Rails Form on a Radio Button Selection
So I have found the precise solution (thanks for the input guys, it helped me redefine my Google searches). Everyone was on the right track, but none were spot on.
All that was needed was to add 'false, :onclick => "this.parentNode.submit();"' to the radio_button_tag form helper. The false is selected or not, and the rest is obvious.
The correct solution now looks like:
<% form_tag({ :controller => "votes", :action => "create", :id => @item.id } ) do %>
<% for i in 1..10 do %>
<%= radio_button_tag :rating, i, false, :onclick => "this.parentNode.submit();" %> <%=h i %>
<% end %>
<% end %>
Simultaneously select radio button and submit form in Rails
You can submit a form without explicitly clicking the submit button with a few lines of custom JavaScript code.
There are a few ways to do it.
Option 1 - :onclick
option
Using the radio_button
helper,
<%= f.radio_button :plan_id, 1 %>
you can add an onclick
option which takes a string of JavaScript code
<%= f.radio_button :plan_id, 1, onclick: "alert('Hello world!');" %>
In the onclick
code, you can use jQuery to select your form and then submit it. What selector you use is up to you.
// data attributes (my preference because it's explicit and flexible)
$('[data-target=my-form]')
// using jQuery's closest() method; "this" will refer to the radio button you clicked
$(this).closest(form)
// an ID or class
$("#my-form")
$(".my-form")
Once you have the form selected, you just need to call the submit
method on it.
Putting it all together,
<%= f.radio_button :plan_id, 1, onclick: "$(this).closest('form').submit();" %>
Option 2 - UJS option
Unobtrusive JavaScript is the process of adding behavior to the DOM via handlers in your JavaScript code which respond to events and trigger actions accordingly.
This option has the following benefits
- It's modular and can be used on other input fields and forms
- It keeps the JavaScript out of the view
In this situation, we'll create a "submit on click" behavior that we can use to enhance your radio button with that behavior.
First the JavaScript event and handler
$(document).on("click", "[data-behavior=submit-on-click]", function() {
$form = $(this).closest('form'); // select the form
$form.submit(); // submit it
});
Now append that special data attribute to the radio button itself to enable the behavior.
<%= f.radio_button :plan_id, 1, data: { behavior: "submit-on-click" } %>
My convention is to use the data-behavior
data attribute, but any selector is fine.
The nice part about this approach is that if you have multiple radio buttons, you can give them all the same behavior by just adding the same data attribute to each.
Additional Resources
- http://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html#unobtrusive-javascript
- https://signalvnoise.com/posts/3167-code-spelunking-in-the-all-new-basecamp <= "JavaScript Behaviors" section
How to set the value of radio button after submitting form?
Apparently, adding a checked attribute for all the radio buttons causes the last radio button to be always selected. So what I did is to just add a checked attribute if the params matched the radio button.
So for my example, I just used a helper to generate the appropriate radio button like so:
def ad_type_radio_button(ad_type)
selected_ad_type = params[:ad_type] || "free"
if selected_ad_type == ad_type
radio_button_tag(:ad_type, ad_type, :checked => true)
else
radio_button_tag(:ad_type, ad_type)
end
end
And have this in my view:
= ad_type_radio_button("free")
I know it's far from elegant, but it behaves correctly now.
How to render input form based on radio button checked in rails simple form
Just bind the change
event to your radio buttons like so, and add/remove a specific class for your form groups:
$(document).ready(function() {
$('input[type="radio"][name="job_application_type"]').change(function() {
if (this.value == 'Email') {
$('.form-group.show-job-url').addClass('form-group--inactive');
$('.form-group.show-job-email').removeClass('form-group--inactive');
}
else if (this.value == 'Url') {
$('.form-group.show-job-url').removeClass('form-group--inactive');
$('.form-group.show-job-email').addClass('form-group--inactive');
}
});
});
Remove your stying from form groups and place it under this form-group--inactive
class in your css file.
.form-group--inactive { display: none; }
Ruby on Rails - Preserve radio button selected on edit view
You shouldn't need two separate forms for this. You can do it with just one, and by using form_for (https://api.rubyonrails.org/v5.1/classes/ActionView/Helpers/FormHelper.html) instead of form_tag. When you have an a model to operate on, you should use form_for. form_tag is for forms without backing models. In the same vein, radio_button_tag is when you don't have a backing model, and radio_button (https://apidock.com/rails/ActionView/Helpers/FormHelper/radio_button) is when you do. Since you have a model, you should go the form_tag route. I suggest changing this around to be(assuming you have a 'work' attribute on your GuideDogForm model):
edit.html.erb (you can copy and paste this in to new.html.erb and it should work like you expect for new records)
<%= form_for @guidedoguser do do |f| %>
<%= f.radio_button :work %>
<% end %>
controller:
class GuideDogFormsController < ApplicationController
def new
@guidedoguser = GuideDogForm.new
end
def create
@guidedoguser = GuideDogForm.new(guide_dog_params)
if @guidedoguser.save
GuideDogMailer.delay_for(10.seconds, retry: true).create(@guidedoguser)
render nothing: true, status: 200
else
render nothing: true, status: 400
end
end
def edit
@guidedoguser = GuideDogForm.where(rg: params[:rg]).first
end
def update
@guidedoguser = GuideDogForm.where(rg: params[:rg]).first
if @guidedoguser.update_attributes(guide_dog_params)
redirect_to guide_dog_form_path(@guidedoguser)
else
render 'edit'
end
end
private
def guide_dog_params
# note if you have more fields you want to persist in your model from your form, you will
# need to add them here after :work
params.require(:guide_dog_form).permit(:work)
end
end
Rails 5 ajax form: submit form on clicking one of the 2 radio buttons in Ajax
After extensive searching for why this happens & how to fix it in the easiest way, I found this issue in Rails 5.2 & thanks to this solution from Padi we should use this code to make it work as expected:
// Get hold of the form object
form = document.querySelector('form');
// Use the Rails fire helper
Rails.fire(form, 'submit');
Getting radio button selection using Rails
See
http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-radio_button
Also
http://guides.rubyonrails.org/form_helpers.html
Section 1.3.2, radio_button_tag
And last but not least,
Labels for radio buttons in rails form
Related Topics
Ruby Array to JavaScript Array
How to Prevent the Chrome Developer Tools Console from Logging Image 404 Errors
Rails - How to Include JavaScript Files Only on Certain Pages
How to Geocode 20 Addresses Without Receiving an Over_Query_Limit Response
Uint8Array to String in JavaScript
Syntaxerror: Unexpected Token Function - Async Await Nodejs
How to Include HTML in a Js Rails Response
Selectionstart/Selectionend on Input Type="Number" No Longer Allowed in Chrome
Ruby Methods Within JavaScript Within Haml
Understanding Asynchronous Code in Layman's Terms
Passing Functions to Settimeout in a Loop: Always the Last Value
Faye Ruby Client Is Not Working
JavaScript Equivalent of Rails Try Method
JavaScript Loops: For...In VS For
How to Print an Iframe from JavaScript in Safari/Chrome
Rake Db:Create - Could Not Find a JavaScript Runtime
How to Plug a JavaScript Engine with Ruby and Nokogiri
Crbug/1173575, Non-Js Module Files Deprecated. Chromewebdata/(Index)꞉5305:9:5551