Ruby On rails, check if the checkbox is not empty - ruby-on-rails

I have a checkbox and before I click on a submission button, I want to check if a checkbox is empty? if it is checked, a notification error should be shown.
<script src="/assets/rails.validations.js" type="text/javascript"></script>
<%= form_for Groupsnorm.new, url: what_to_do_arraydbs_path ,method: :get ,:validate => true do |f| %>
<div class="field_label">
<%= f.label :group_name%>:
</div>
<div class="field">
<%=f.text_field :group_name %>
</div>
<%= submit_tag "Submit", :commit =>"pictures" %>
<% #files.each do |file| %>
<p><td> <%= check_box_tag "files[]", file.id %></td><%= arraydb.arraydb_file_name %></p>
<%end%>
<%end%>
and JavaScript looks something like this:
$(function validateCheckbox() {
$('#notifications').ready(function() {
$.notification(
{
content: text,
showTime: false,
timeout: 5000,
icon: "9",
}
);
});
});
How is it possible to check if the checkbox is empty? Or is it possible to do a client side validation so that "submit" button will not be clickable if checkbox is empty?

in you controller write
if params[:CheckBoxNameAttribute]
{
// source code here
}
this checks whether your checkbox is checked or not

Related

New search form partial is redirecting to my main index page for the model

I have an events model and I have an address field where I have some geolocation logic being implemented. On my main index page, I'm rendering a search form partial that works just fine to be all to search all of the events in my database.
Here's the original search form:
<%= search_form_for #q,
data: { controller: "places", action: "google-maps-callback#window->places#initMap" } do |f| %>
<div class="formlook">
<div class="event-search-container">
<div class="event-name">
<%= f.label "Event name", class: "form-label" %>
<%= f.search_field :name_cont, placeholder: "Any event", class: "form-control" %>
</div>
<div class="geolocation">
<%= f.label "Geolocation", class: "form-label" %>
<%= f.search_field :address_or_city_or_state_or_country_or_continent_cont_all, class: "form-control", placeholder: "Search by continent, country, state, or city", data: { places_target: "field" } %>
</div>
<div class="dancestyle">
<%= f.label "Dance style", class: "form-label" %>
<%= f.select(:dance_styles_id_in, DanceStyle.all.pluck(:name, :id), { :include_blank => "All dance styles" }, { class: "form-select", id: "select-dancestyle", multiple: true, placeholder: "Any dance style" }) %>
</div>
<div class="eventtype">
<%= f.label "Event Type", class: "form-label" %>
<%= f.select :event_type_id_in, EventType.all.pluck(:name, :id), { :include_blank => "All event types" }, { id: "select-artist", multiple: true, placeholder: "Any event type", class: "form-select" } %>
</div>
<div class="month">
<%= f.label "Month", class: "form-label" %>
<%= f.select(:event_month_in, (Date::MONTHNAMES[1..12]), { prompt: "Any month" }, { id: "select-month", :include_blank => "Any month", class: "form-select", multiple: true }) %>
</div>
<div class="year">
<%= f.label "Year", class: "form-label" %>
<%= f.select :event_year_in, Date.today.year-2 .. Date.today.year+3, { prompt: "Any year" }, { id: "select-year", include_blank: true, class: "form-select", multiple: true } %>
<br>
</div>
</div>
</div>
<%= f.submit "Search!", class: "button-orange" %>
<% end %>
I'm now creating specific event index pages for particular cities now. So I want to be able to use the other search parameters from my main index page without the name or the address field. So I created a new html erb file with a new scope based off the event model for a particular city:
<div class="container index">
<div>
<h1>Dance Events in Austin, Texas!</h1>
<br>
<div class="help-attn">
<p>All of the search options work together! Create your own search filters to find the events you want!</p>
</div>
<%= render 'events/local_search_form' %>
<br>
<h5>Currently displaying <%= pluralize(#events.in_austin.count, "event") %>. </h5>
<br>
</div>
<h3>Upcoming Events</h3>
<div class="event-list-wrapper">
<% #events.upcoming_events.in_austin.each do |event| %>
<%= render 'event', event: event %>
<% end %>
</div>
<h3>Past Events</h3>
<div class="event-list-wrapper past-event">
<% #events.past_events.in_austin.each do |event| %>
<%= render 'event', event: event %>
<% end %>
</div>
I also needed to add the def atx_index to my event model with the same parameters as the def index since in my head they are both index pages, just one has a different scope.
From above you will see that I created a different search form partial to reflect the two fields I don't need anymore, here's the new search form partial.
<%= search_form_for #q do |f| %>
<div class="formlook">
<div class="local-search-container">
z <%= f.hidden_field :address_or_city_or_state_or_country_or_continent_cont_all, value: [""] %>
<div class="dancestyle">
<%= f.label "Dance style", class: "form-label" %>
<%= f.select(:dance_styles_id_in, DanceStyle.all.pluck(:name, :id), { :include_blank => "All dance styles" }, { class: "form-select", id: "select-dancestyle", multiple: true, placeholder: "Any dance style" }) %>
</div>
<div class="eventtype">
<%= f.label "Event Type", class: "form-label" %>
<%= f.select :event_type_id_in, EventType.all.pluck(:name, :id), { :include_blank => "All event types" }, { id: "select-artist", multiple: true, placeholder: "Any event type", class: "form-select" } %>
</div>
<div class="month">
<%= f.label "Month", class: "form-label" %>
<%= f.select(:event_month_in, (Date::MONTHNAMES[1..12]), { prompt: "Any month" }, { id: "select-month", :include_blank => "Any month", class: "form-select", multiple: true }) %>
</div>
<div class="year">
<%= f.label "Year", class: "form-label" %>
<%= f.select :event_year_in, Date.today.year-2 .. Date.today.year+3, { prompt: "Any year" }, { id: "select-year", include_blank: true, class: "form-select", multiple: true } %>
<br>
</div>
</div>
</div>
<%= f.submit "Search!", class: "button-orange" %>
<% end %>
So the specific city event index page is displaying properly following the scope but when I use the search I'm redirected to the main event index page with the search parameters that I inputted. I'm not understanding how the two different search form partials are both linked to the main event index page.
How do I get the new search form partial for the specific city index page to display the search results on its corresponding page?
The issue to my redirect form issue was that I need to set the URL of the new form I created, so I was able to get the proper path names from the routes.
My initial implementation though had my configuring the form specifically and since I wanted to reuse the form on multiple pages for the individual local cities, I was lucky to find an old 7 year old SOF article that referred to setting the url in the render line like this:
<%= render 'events/local_search_form', { url: atx_index_path } %>
and then calling that url string in the local_search_form like so:
<% if local_assigns.has_key? :url %>
<%= search_form_for #q, { url: url } do |f| %>
and now I can simply change the url path for each html.erb file I create for each individual city! I didn’t know about the local assigns!

Rails Submit button not submitting

I've moved from BS3 to Materialize so I am going through and changing my forms - I have 4 forms that are extremely similar, but as I switched the first one over it's no longer submitting. The button doesn't even seem like it's getting clicked, but I tied a generic 'logMe' function to it and sure enough it is.
My routes are the exact same for both, the new form is
<div class="row">
<%= form_with(model: #statement, local: true) do |form| %>
<% if #statement.errors.any? %>
<% #statement.errors.full_messages.each do |message| %>
<script>
$(function() {
Materialize.toast("<%= message %>", 3000);
});
</script>
<% end %>
<% end %>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">account_circle</i>
<!--<label for="icon_prefix">SoW Type:</label>-->
<%= form.label :statement_type, 'Type:' %>
<%= form.text_field :statement_type, :id => "disabled", :value => (params[:statement_type]), readonly: true, :disabled => true %>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<i class="material-icons prefix">contacts</i>
<%= form.label :name, "Name:" %>
<%= form.text_field :name, :id => 'required_field1' %>
</div>
<div class="input-field col s6">
<i class="material-icons prefix">contacts</i>
<%= form.label :cost, "Cost:" %>
<%= form.text_field :cost, :id => 'required_field2' %>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<i class="material-icons prefix">date_range</i>
<%= form.label :start_date, "Start Date" %>
<%= form.text_field :start_date, :class => 'datepicker', "data-provide" => 'datepicker', :id => 'required_field4', :placeholder => "YYYY-MM-DD" %>
</div>
<div class="input-field col s6">
<i class="material-icons prefix">date_range</i>
<%= form.label :end_date, "End Date" %>
<%= form.text_field :end_date, :class => 'datepicker', "data-provide" => 'datepicker', :id => 'required_field5', :placeholder => "YYYY-MM-DD" %>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">perm_contact_calendar</i>
<%= form.collection_select(:client_id, current_user.clients.order(:name),:id,:name, :class => "browser-default", :prompt => "Choose a client" ) %>
</div>
</div>
<div class="row">
<div class="col s12">
<%= form.submit 'Submit', :class =>'btn btn-default', :id => 'register', :onclick => "testMe()"%>
</div>
</div>
<% end %>
</div>
<script type="text/javascript">
$(document).ready(function (){
$('select').material_select();
validate();
$('#required_field1, #required_field2').change(validate);
});
function testMe(){
console.log('hi')
}
function validate(){
if ($('#required_field1').val().length > 0 &&
$('#required_field2').val().length > 0
){
$("input[type=submit]").prop("disabled", false);
}
else {
$("input[type=submit]").prop("disabled", true);
}
}
var from_$input = $('#required_field4').pickadate({
selectMonths: true, // Creates a dropdown to control month
selectYears: 15, // Creates a dropdown of 15 years to control year,
today: 'Today',
clear: 'Clear',
close: 'Ok',
closeOnSelect: true,
format: 'yyyy-mm-dd'
}),
from_picker = from_$input.pickadate('picker')
var to_$input = $('#required_field5').pickadate({
selectMonths: true, // Creates a dropdown to control month
selectYears: 15, // Creates a dropdown of 15 years to control year,
clear: 'Clear',
close: 'Ok',
closeOnSelect: true,
format: 'yyyy-mm-dd'
}),
to_picker = to_$input.pickadate('picker')
// Check if there’s a “from” or “to” date to start with.
if ( from_picker.get('value') ) {
to_picker.set('min', from_picker.get('select'))
}
if ( to_picker.get('value') ) {
from_picker.set('max', to_picker.get('select'))
}
// When something is selected, update the “from” and “to” limits.
from_picker.on('set', function(event) {
if ( event.select ) {
to_picker.set('min', from_picker.get('select'))
}
else if ( 'clear' in event ) {
to_picker.set('min', false)
}
})
to_picker.on('set', function(event) {
if ( event.select ) {
from_picker.set('max', to_picker.get('select'))
}
else if ( 'clear' in event ) {
from_picker.set('max', false)
}
})
</script>
I've tried commenting out all JS, switching it to a regular button, linting it and using Rubocop but I don't see anything off. I went through the HTML to make sure the button was inside the form, and it is.
This isn't the first form I've transitioned, but the first I'm having issues with.
(I assume only the view is relevant since it isn't getting to the controller at this point.)
Just to be safe - The view rendering the form is
<div class="row">
<div class="col s12"><span class="flow-text" style="text-align: center;"><h1>New <%= params[:statement_type] %></h1></span></div>
</div>
<% if params[:statement_type] == 'Proposal' %>
<%= render 'proposal_form' %>
<% elsif params[:statement_type] == 'Concept' %>
<%= render 'concept_form' %>
<% elsif params[:statement_type] == 'SoW' %>
<%= render 'sow_form' %>
<% elsif params[:statement_type] == 'Misc' %>
<%= render 'misc_form' %>
<% end %>
<%= link_to 'Back', statements_path %>
SoW + Proposal work. SoW doesn't.
My issue ended up not being HTML based, but Rails based in the end.
My static element that is populated by a param was causing the issue.
<%= f.text_field :statement_type, :id => "disabled", :value => (params[:statement_type]), readonly: true %>
By removing the id: disabled it resolved the inability for the Submit button to submit. Unfortunately, it also makes MaterializeCSS back to highlighting the field when I select it, but my issue was the Submit button not working.

How to use radio button to not send data to the server?

I am able with the radio button and a little javascript to toggle between the two categories, but even if one category is hidden it's data still sends.
challenge.rb
class Challenge < ActiveRecord::Base
scope :oneshot, -> { where(categories: 'One-Shot') }
scope :ongoing, -> { where(categories: 'Ongoing') }
_form
<%= form_for(#challenge) do |f| %>
<%= f.text_field :action %>
<% Challenge::CATEGORY.each do |c| %>
<%= label(c, c) %>:
<%= f.radio_button(:category, c, :class => "date-format-switcher", checked: (c=='One-Shot')) %>
<% end %>
<div id='id_of_first_div'>
<%= f.date_select :deadline %>
</div>
<div id='id_of_second_div'>
<%= f.date_select :date_started %>
</div>
<% end %>
<script>
$(function(){
$('#id_of_second_div').hide();
$('#challenge_category_one-shot').click(function(){
$('#id_of_first_div').show().attr('disabled', false);
$('#id_of_second_div').hide().attr('disabled', true);
});
$('#challenge_category_ongoing').click(function(){
$('#id_of_first_div').hide().attr('disabled', true);
$('#id_of_second_div').show().attr('disabled', false);
});
});
</script>
Radio Button HTML
<input class="date-format-switcher" type="radio" value="One-Shot" checked="checked" name="challenge[category]" id="challenge_category_one-shot" />
<input class="date-format-switcher" type="radio" value="Ongoing" name="challenge[category]" id="challenge_category_ongoing" />
Adapting Fiddle
<input id='a-selector' type='radio' name='selector' value='A' checked/> A
<input id='b-selector' type='radio' name='selector' value='B'/> B
<div id='details'>
<div id='for-a'>
<%= f.date_select :deadline, include_blank: true, selected: Date.current %>
</div>
<div id='for-b'>
<%= f.date_select :date_started, include_blank: true, selected: Date.current %>
</div>
</div>
<script>
var removed = $('#for-b').detach();
$('#a-selector').click(function() {
$('#details').append(removed);
removed = $('#for-b').detach();
})
$('#b-selector').click(function() {
$('#details').append(removed);
removed = $('#for-a').detach();
})
</script>
Setting a form element as disabled only disables user interaction with it; it doesn't remove it from the form's data (although your jQuery code is actually setting the div to disabled, which does nothing, but fixing that wouldn't help at all). What you want to do instead is clear the value of the date elements, e.g.,
<script>
$(function(){
$('#id_of_second_div').hide();
$('#challenge_category_one-shot').click(function(){
$('#id_of_first_div').show();
$('#id_of_second_div').hide();
$('#id_of_second_div select').value('')
});
$('#challenge_category_ongoing').click(function(){
$('#id_of_second_div').show();
$('#id_of_first_div').hide();
$('#id_of_first_div select').value('')
});
});
</script>
Though for that to work, you will need to add include_blank: true as an option to your date_select tags:
<%= f.date_select :deadline, include_blank: true %>
This will add the empty value as an option to your date selects, so that the above code can reset them to that empty value.
I'd also like to note -- all of this is just front-end logic, which any malevolent (or curious) user can circumvent. Your backend code (i.e., your controller) should handle discarding the fields you don't need based on your business logic, too.

How to submit a form with ajax if two parameters are set

I have a simple rails form and want to submit the form when the two parameters are set without the click of a submit button. How can i write a simple jquery ajax request to do this.
my form below is
<div class="row-fluid">
<div class="span7">
<%= form_tag search_by_group_admin_codes_path, :method => :get, class: "well form-inline" do %>
<p class="f_legend">Black List Codes</p>
<div class="input-prepend">
<span class="add-on ad-on-icon"><i class="icon-qrcode"></i></span>
<%= text_field_tag 'q', #q, placeholder: "between", id: "q" %>
<%= text_field_tag 's', #s, placeholder: "to", id: "s" %>
</div>
<% end %>
</div>
</div>
Any help thanks? i am Not too good at ajax in rails without the click of a button
$(function(){
$('input').on("input", checkInput)
//$('input').on("keyup", checkInput)
})
function checkInput(ev){
if($('#q').val != '' && $('#q').val().length == 8 && $('#s').val != '' && $('#s').val().length == 8 )
{
$(this).closest('form').submit()
}
}

show rest of a form if a checkbox is ckecked in ruby on rails

I need to ask to my user if will pay a service with credit card...if it checked the option pay_with_card? it must show the rest of the form, that ask for other data like card number, mail, etc. if the user don't checked it, it must show a message, the question is...how can I do this? thanks in advance
<%= form_for(#product) do |f| %>
<%= f.label :pay_with_card? %>
<%= f.check_box :pay_with_card,{}, "Yes", "No"%>
<div>
<%= f.label :card_number %> <%= f.text_field :card_number %>
</div>
<div>
<%= f.label :mail %> <%= f.text_field :mail %>
</div>
<% end %>
Make the card number/mail details div style="display:none;", then add some javascript to the checkbox to change it to display:block;
Something like this:
<%= form_for(#product) do |f| %>
<%= f.label :pay_with_card? %>
<%= f.check_box :pay_with_card,{}, "Yes", "No"%>
<div id="card_details" style="display:none;">
<%= f.label :card_number %> <%= f.text_field :card_number %>
<%= f.label :mail %> <%= f.text_field :mail %>
</div>
<% end %>
<script type="text/javascript">
var checkbox = document.getElementById('product_pay_with_card');
var details_div = document.getElementById('card_details');
checkbox.onchange = function() {
if(this.checked) {
details_div.style['display'] = 'block';
} else {
details_div.style['display'] = 'none';
}
};
</script>
How about using jQuery?
First, wrap your credit card fields in a div with class credit_card_fields and than add this JS code to your page:
$("input[type='checkbox']#pay_with_card").on('change', function(){
$('.credit_card_fields').toggle();
});
You can use JS for it or move pay_with_card out of form like:
<%= link_to 'pay with card', your_current_path(:pay_with_card => 1) %>
<%= form_for(...) do |f| %>
<% if params[:pay_with_card] %>
<%= # fields for card %>
<% end %>
<% end %>
You can do it through jQuery, for example:
$ ->
$('select#pay_with_card').change ->
if $(this).val() == 'yes'
$('.card_block').slideDown('fast')
else
$('.card_block').slideUp('fast')
assumed that part of the form with payment card is included in the div with .card_block class
Ok my solution is this: all the code in the view, if a user check pay_with_card...(mi code is in spanish) it shows the complete form...if is not checked don´t show nothing, just the same checkbox asking for payment... thanks guys.
function mostrar (){
var checkbox = document.getElementById('chk_tarjeta');
if (checkbox.checked)
document.getElementById("card_details").style.display = "block";
else
document.getElementById("card_details").style.display = "none";
</script>
<h1>Forma de Pago</h1>
<%= form_for(#product) do |f| %>
<div id="product_pay_with_card">
<div >
<%= f.label :paga_con_tarjeta? %></br>
<%= f.check_box :paga_con_tarjeta, :id => "chk_tarjeta", :onclick => "mostrar();" %>
<div>
</div>
</div>
<div id="card_details" >
<div>
<%= f.label :numero_de_tarjeta %></br>
<%= f.text_field :numerotarjeta %>
</div>
<div>
<%= f.label :codigo_de_seguridad %></br>
<%= f.text_field :codigoseguridad %>
</div>
This worked for me with a form_with model and bootstrap
Change my_hidden_form with an id that makes sense for your form.
Original code is haml
= form_with scope: :model, url: models_path, local: true do |form|
.row
.col-6
.form-group
%h5.mb0 THE CASE TO TICK
= form.check_box :form_value, {:data => {:aria => {controls: :my_hidden_form, expanded: false}, :toggle => "collapse", :type => "checkbox", :target => "#my_hidden_form" }}
.row
.col-6
.form-group.collapse#my_hidden_form
%h5.mb0 THE FORM TO SHOW WHEN CASE IS TICKED
= form.text_field :name, placeholder: "A name"
.row
.col-md-12.text-right
= form.submit 'Submit', class: "btn btn-primary"
Converted to erb/html with https://haml2erb.org/
<%= form_with scope: :model, url: models_path, local: true do |form| %>
<div class="row">
<div class="col-6">
<div class="form-group">
<h5 class="mb0">THE CASE TO TICK
<%= form.check_box :form_value, {:data => {:aria => {controls: :my_hidden_form, expanded: false}, :toggle => "collapse", :type => "checkbox", :target => "#my_hidden_form" }} %>
</h5>
</div>
</div>
</div>
<div class="row">
<div class="col-6">
<div class="form-group collapse" id="my_hidden_form">
<h5 class="mb0">THE FORM TO SHOW WHEN CASE IS TICKED
<%= form.text_field :name, placeholder: "A name" %>
</h5>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 text-right">
<%= form.submit 'Submit', class: "btn btn-primary" %>
</div>
</div>
<% end %>
Since the approach suggested by #Unixmonkey didn't work for me, here's a slight variation I put together using an event listener.
<script type="text/javascript">
const checkbox = document.getElementById('product_pay_with_card');
const details_div = document.getElementById('card_details');
checkbox.addEventListener("change", (event) => {
if (event.currentTarget.checked) {
details_div.style['display'] = 'block';
}
else {
details_div.style['display'] = 'none';
}
});
</script>

Resources