Select/Deselect multiple check boxes using Jquery in loop(Rails) - javascript

I working on RoR, I have a two loops inside that i am displaying records with check boxes.
<%= form_tag some_path, :method => 'post' do %>
For loop
<%= check_box_tag 'ids[]', value %> Name
For loop
<%= check_box_tag 'ids_of_second_loop[]', value %> Name
end
end
<%= submit_tag "Next" %>
<% end %>
Now i wanted to apply a jquery where i can select/ deselect the checkboxes.
I can do if its not in the loop straight forward,
I am referring below link for implementation,
link
Loop Output...
How to achieve it...

I would do something like
<%= form_tag some_path, :method => 'post' do %>
For loop
<%= check_box_tag 'ids[]', value, class: 'parent' %> Name
<div class='children'>
For loop
<%= check_box_tag 'ids_of_second_loop[]', value %> Name
end
</div>
end
<%= submit_tag "Next" %>
<% end %>
note that "div class='children'" after the checkbox and the class "parent" on all parent checkboxes
then, javascript
$('input.parent').on('change',function(){
$(this).next('.children').find('input[type=checkbox]').prop('checked',$(this).prop('checked'));
})
it searches the next div with class 'children' after the clicked checkbox, then, it searches all inputs with type=checkbox inside that div, and sets the prop "checked" to the value returned by the current input clicked

Working fiddle :
$("#button").click(function () {
if($("#test")[0].checked)
{
$("#test")[0].checked = false;
}
else
{
$("#test")[0].checked = true;
}
});
http://jsfiddle.net/q8wvv1ky/

Related

Jquery .on change() hitting both all select fields in js.erb file ruby on rails

I am new to Javascript and Jquery in Rails so apologies if something like this has been asked before. I have been stuck on this issue all day now.
I have three fields in a form, "from location," "to location," and "quantity". When the "from location" select field is changed, I'd like for:
the "to location," to change to remove the selected field in the "from location"
the "quantity" to reflect the available quantity at the "from location."
I am writing this in my edit.js.erb file for my item model.
I have given all fields different classes and am referencing the specific field by class but the .on change() is firing for all select fields.
(The variable fohInventoryItems is provided via a script block in this model's index page.)
Here's my code:
var selectedItemClass = <%=#item.id%>
(document).on('change', $('select.' + selectedItemClass + "." + 'from-select').eq(0), function() {
});
And her is my code in _form.html.erb for this model:
<%= form_for item, remote: true, format: "js" do |f| %>
<%= f.label :from_location %><br>
<%= f.collection_select :location_ids, item.locations.uniq, :id, :name, {selected: item.locations.uniq.first}, { class: "form-control #{item.id} from-select", } %><br>
<%= fields_for :line_items, item.line_items.build do |l| %>
<%= l.label :to_location %><br>
<%= l.collection_select :location, Location.all, :id, :name, {}, { class: "form-control #{item.id} to-select" } %><br>
<%= f.label :quantity %><br>
<%= f.select :quantity, (Array (1..item.quantity)), {}, { class: "form-control #{item.id}" } %>
<%end%>
<br>
<div style="text-align: center;">
<%= f.submit "Move", class: "#{item.id} submit" %><br>
</div>
<% end %>
When using on() as a delegated event handler, the second argument is used as a filter internally to check if the elements match a selector.
The documentation clearly states that the syntax is
.on( events [, selector ] , handler )
With seleector being
selector
Type: String
A selector string to filter the descendants of
the selected elements that will call the handler. If the selector is
null or omitted, the handler is always called when it reaches the
selected element.
The reason for it being a string, is that the elements will be checked against it, so it can't be another jQuery collection.
...meaning you have to change your code to
$(document).on('change', '.' + selectedItemClass + 'from-select', function() {...

Access form_group div via id

I want to perform a check to provide instant validation feedback on the input of a field in my bootstrap form for my Profiles model using java/coffee-script. My current solution is working but feels rather clunky and I would like to improve it.
Here are some code examples of what I'm doing.
app/views/profiles/_form:
<%= bootstrap_form_for(#profile, layout: :horizontal, html: {id: "profile-form"} ) do |f| %>
<%= f.text_field :name %>
<%= f.text_field :number, id: "number-field" %> //Field to check
<%= form_group do %>
<%= f.primary %>
<% end %>
<% end %>
app/assets/javascript/profile_number_control.coffee:
$(document).on 'ready page:load', ->
$field = $("#number-field")
$group = document.getElementById("profile-form").childNodes[5]
numberPattern = "^(19|20)[0-9]{6}-[0-9]{4}$"
$helpBlock = $group.getElementsByClassName("help-block")[0]
$field.keyup ->
//This works fine, just wanted to show what is going on
if inputIsValid()
set $group class to " has-success"
set $helpBlock message to successful
else
set $group class to " has-error"
set $helpBlock message to corresponding error message
Here is the problem. I want this script to work for both profile#new and profile#edit, but since the array of elements given by document.getElementById("profile-form").childNodes differs in length depending of the current view I can not use the same index (5 in the example) for both #new and #update.
Does anyone know how to set an id to that specific form_group in my view? Or do I have to actually write out the whole html code to be able to place an id there properly?
This might help !
<%= bootstrap_form_for(#profile, layout: :horizontal, html: {id: "profile-form"} ) do |f| %>
<%= f.text_field :name %>
<%= f.text_field :number, :input_html => { id: "number-field" } %> //Field to check
<%= form_group do %>
<%= f.primary %>
<% end %>
<% end %>

Using JavaScript/Jquery to show forms with the same id/class in Ruby

I want to have a button for retweets in my web-application. When I press the button I want a form to display in order to add my own text to the tweet.
I implemented this . However I have a problem: all my forms and buttons contain the same id and class, so you can imagine that when I press a button it will display the first form with that id/class instead of the one that it has to show. How can I show the form that I have to show ?
Here are only the parts of the code that contain retweet part(the other parts are not important I think for the problem but I can post them if someone wants me to) :
<button type="buton" id="retweet-button">retweet</button>
<%= form_for(current_user.tweets.build,url: retweet_act_path, method: :post, html: { multipart: true, :class => "retweet_form" }) do |f| %>
<%= f.hidden_field :original_tweet_id, value: tweet.id %>
<%= f.text_area :content, placeholder: "Add a message to the tweet..." %>
<%= f.submit "Retweet"%>
<% end %>
And the JS:
<script type="text/javascript">
$(document).ready(function() {
$('.retweet_form').hide(); //Initially form wil be hidden.
$('#retweet-button').click(function() {
$('.retweet_form').show();//Form shows on button click
});
});
</script>
How can I show the form that I have to show when pressing a certain button ? (I guess I have to have a different ID for every button and form , but how ? )
As I understood from the code, you use one button/form pair per tweet. So that, you are able to use tweet ID to generate form ID. To connect button to appropriate form, use data-* fields.
Generation of forms and buttons on Rails side (NOTE: syntax highlight is broken):
<button type="button" class="retweet-button" data-target-form-id="<%= "#retweet-form-#{tweet.id}" %>">retweet</button>
<%= form_for(current_user.tweets.build,url: retweet_act_path, method: :post, html: { multipart: true, :class => "retweet_form", id: "retweet-form-#{tweet.id}" }) do |f| %>
<%= f.hidden_field :original_tweet_id, value: tweet.id %>
<%= f.text_area :content, placeholder: "Add a message to the tweet..." %>
<%= f.submit "Retweet"%>
<% end %>
And JS:
$('.retweet_form').hide();
$('.retweet-button').click(function() {
var formId = $(this).data('target-form-id');
$(formId).show();
});

How to Change Date Format According to User Selection?

How can I change the date :order according to the User's "f.select :categories" choice?
For example when a User goes to the Quantified _form he can select between "Monthly Average" or "One-Time Instance";
If he selects "Monthly Average" I want the _results_fields.html.erb to provide the date selection as ":order => [:month, :year]" if he selects "One-Time Instance" I want the _results_fields.html.erb to provide the date selection as ":order => [:month, :day, :year]
Ideally this would be done dynamically via javascript, but I would be happy to accept an answer that does it via the view.
_results_fields.html.erb
<div class="nested-fields">
<div class="form-group">
<%= f.text_field :result_value, class: 'form-control', placeholder: 'Enter Result' %>
<br/>
<%= f.date_select :date_value, :order => [:month, :year], class: 'date-select' %>
<%= link_to_remove_association "Remove Result", f %>
</div>
</div>
_form.html.erb
<%= form_for #quantified do |f| %>
<div class="america">
<%= f.select :categories, Quantified::CATEGORIES %>
<br/>
<br/>
<div class="form-group">
<%= f.text_field :name, class: 'form-control', placeholder: 'Enter Name' %>
</div>
<div class="form-group">
<%= f.text_field :metric, class: 'form-control', placeholder: 'Enter Metric' %>
</div>
<div id="results">
<%= f.fields_for :results do |result| %>
<%= render 'result_fields', :f => result %>
<% end %>
</div>
<div class="links">
<%= link_to_add_association 'add result', f, :results %>
</div>
<%= f.submit %>
</div>
<% end %>
quantified.rb
class Quantified < ActiveRecord::Base
belongs_to :user
scope :averaged, -> { where(categories: 'Monthly Average') }
scope :instance, -> { where(categories: 'One-Time Instance') }
has_many :results
accepts_nested_attributes_for :results, :reject_if => :all_blank, :allow_destroy => true
CATEGORIES = ['Monthly Average', 'One-Time Instance']
end
Github: https://github.com/RallyWithGalli/ruletoday
Thank you for your time.
The answer here was to use some jquery provided by the gem that was being used to add the date selects, as well as some jquery of our own
First things first, we rig up the checkboxes with a click() event, that hides anything with the class 'day' if instance is checked, and shows it if not.
$('.date-toggle').click(function(){
if( $(this).attr('id') == 'instance') {
$('.day').show();
} else {
$('.day').hide();
}
});
The trick here is to use the rails date select option :with_css_classes on the date select, so that it looks like this:
<%= f.date_select :date_value, :order => [:month, :day, :year], :with_css_classes => true, class: 'date-select' %>
This causes each included field to get a class corresponding to its name, hence our reference to '.day' up there.
The next important part, however, because he is using a gem called cocoon to add new elements that included date fields, we had to use some of their jquery event bindings to make sure that the new ones got the right action applied to them.
$('#container').on('cocoon:after-insert', function(e, insertedItem) {
if($('#instance').is(':checked')) {
$('.day').show();
} else {
$('.day').hide();
}
});
Technically, the $('.day').show() is not necessary, because it defaults to being shown, but this, to me, gets across the intent a little clearer.
I think my solution is a little bit messy, but hopefully it gives you an indication of my train of thought and give you something to build upon.
I have changed your categories to work with a radio button group because the select field is a bit weird for 2 elements (subjective I know), to change it back to a select form,simply keep your code as is, but you will need to check the value of the select dropdown using jQuery .change() or some other vanilla Javascript way...
You haven't provided any controller names, so I didn't know how to name my JS file, but hopefully you know how to integrate.
IMO, I'm not sure why this needs AJAX, so maybe you can explain to me where that comes in.
_form.html.erb
<%= Quantified::CATEGORIES.each do |c| %>
<%= f.radio_button(:category, c) %>
<%= label(c, c) %>
<% end %>
_results_fields.html.erb
<%= f.date_select :date_value, :order => [:month, :year], class: 'date-select-my' %>
<%= f.date_select :date_value, :order => [:month, :year], class: 'date-select-mdy' %>
vanilla.js
$(document).ready(function(){
$('.date-select-mdy').hide();
$('.date-select-mdy').attr("disabled", true);
$('input[name$=\category\']').click(function() {
var target_value;
target_value = $(this).val;
if (target_value === 'Monthly Average') {
$('.date-select-my').show();
$('.date-select-mdy').hide();
$('.date-select-my').attr("disabled", false);
return $('.date-select-mdy').attr("disabled", true);
} else {
$('.date-select-my').hide();
$('.date-select-mdy').show();
$('.date-select-my').attr("disabled", true);
return $('.date-select-mdy').attr("disabled", false);
}
});
});
a_little_bit_of_coffee_because_i_dislike_js.coffee
$->
$('.date-select-mdy').hide()
$('.date-select-mdy').attr("disabled",true)
$('input[name$=\category\']').click ->
target_value = $(this).val
if target_value == 'Monthly Average'
$('.date-select-my').show()
$('.date-select-mdy').hide()
$('.date-select-my').attr("disabled",false)
$('.date-select-mdy').attr("disabled",true)
else
$('.date-select-my').hide()
$('.date-select-mdy').show()
$('.date-select-my').attr("disabled",true)
$('.date-select-mdy').attr("disabled",false)
return

Rails: displaying a value dynamically calculated in my form

In my new.html.erb, I have the following:
<%= hidden_field :shipping_charges %>
<%= label_tag :rush_shipment, "Rush My Shipment" %>>
<%= check_box_tag :rush_shipment, :checked => false, :onclick => "add_rush_shipment_charges()" %>
<p>My Shipping charges: <span id="shipping_charges"></span>
In my javascript file, I have the following:
function add_rush_shipment_charges()
{
document.getElementById('shipping_charges').value = 25;
}
When I click on the checkbox, I'm supposed to see 25 appear after Shipping charges, but nothing is happening. Any ideas.
EDIT:
Note that I edited the question to reflect the info I got from answer #1, but I am still not seeing anything.
Where you want to show the shipping charges? Lets assume your view is like:
<%= hidden_field :shipping_charges %>
<%= label_tag :rush_shipment, "Rush My Shipment" %>>
<%= check_box_tag :rush_shipment, :checked => false, :onclick => "add_rush_shipment_charges()" %>
<h3> You shipping charges are: <span id="total_shipping"></span</h1>
Now, after calculating the total costs of shipping, you just update the span
function calculate_total_costs(){
//cost calculation logics
document.getElementById('total_shipping').value = TOTAL_COSTS
}
Now, call the function calculate_total_costs() when you want!
Your checkbox tag is incorrect:
<%= check_box_tag :rush_shipment, :checked => false, :onclick => "add_rush_shipment_charges()" %>
Should be:
<%= check_box_tag :rush_shipment, "yes", false, :onclick => "add_rush_shipment_charges()" %>
Until you fix that, the JavaScript method will not be called on clicks.
The JavaScript method is not correct either, as you can not set standard DOM, such as a span, using .value, you must use innerHTML (or better, use jQuery's .html() method for better cross-browser support):
function add_rush_shipment_charges()
{
document.getElementById('shipping_charges').innerHTML = '25';
}

Categories

Resources