I want something quite simple for my Rails app: a javascript must be run only if one of the previous radio buttons was checked. What I want exactly is that the user has different radio buttons shown to him, with no default checked. When he clicks on a "Run" button, below the radio buttons, two cases:
- the user checked a radio button, then the javascript is run (a div is hidden, and another one is shown)
- the user didn't check a radio button, nothing happens (even more: the browser tells the user that he must checks a radio button, but that is easily done with a
:required => true
option in the radio button)
The code I tried:
HTML.erb code
<%= form_with(model: @pdfrequest, local: true, html: {class: "form-group"}) do |f| %>
<%= f.radio_button :my_param, 'option1' %>
<%= label :opt1, 'option1', :value => 'option1'%>
<%= f.radio_button :my_param, 'option2' %>
<%= label :opt2, 'option2', :value => 'option2'%>
<div class="row mb-3">
<div class="col", id="to_hide">
<%= submit_tag "Run", id: "upload_button" %>
</div>
</div>
<div id="to_show">
<p>Show me!</p>
</div>
<% end %>
I only managed to get the code working on click, no matter if the form is filled or not.
jquery code
$(document).on("click", "#upload_button", function() {
$("#to_show").show();
});
$(document).on("click", "#upload_button", function() {
$("#to_hide").hide();
});
The jquery code is located in my application.js in the assets folder.
I would expect something like this, located in the same file as the html code I provided:
Expected answer
<% if form_with.filled %>
$(document).on("click", "#upload_button", function() {
$("#to_show").show();
});
$(document).on("click", "#upload_button", function() {
$("#to_hide").hide();
});
<% end %>
I found some other questions closely related to this issue, but every time, the condition was a "simple" condition on an object, but not linked to the form itself.
I'm using Rails 5.2.3 and jquery 3.2.1
Thanks.
EDIT
Thanks to this question: Find out whether radio button is checked with JQuery?, I made some progress.
HTML.erb code
<%= form_with(model: @pdfrequest, local: true, html: {class: "form-group"}) do |f| %>
<%= f.radio_button :my_param, 'option1', :id => 'button_check' %>
<%= label :opt1, 'option1', :value => 'option1'%>
<%= f.radio_button :my_param, 'option2', :id => 'button_check' %>
<%= label :opt2, 'option2', :value => 'option2'%>
<div class="row mb-3">
<div class="col", id="to_hide">
<%= submit_tag "Run", id: "upload_button" %>
</div>
</div>
<div id="to_show">
<p>Show me!</p>
</div>
<% end %>
jquery code
$(document).on("click", "#upload_button", function() {
if($('#button_check').is(':checked')) {
$("#to_show").show();
}
});
$(document).on("click", "#upload_button", function() {
if($('#button_check').is(':checked')) {
$("#to_hide").hide();
}
});
So now, it doesn't execute the jquery when no button is checked, but even if a radio button is checked, it's not executed but I couldn't figure out what I did wrong.