HTML Checkbox giving all values - javascript

I know this question seems repeated but I have searched through many sites and am still unable to get my code working.
I'll explain my problem as I paste the code.
Here is my form:
<form action="">
<% position = #deals_daily_count.size - 2 %>
<% num_of_expired_deals = #deals_daily_count[position].size %>
<% loops = 0 %>
<% while loops < num_of_expired_deals %>
<input type="checkbox" class="choice" name="choice[]" value="<%= #deals_daily_count[position][loops] %>"><%= #deals_daily_count[position][loops] %>
<br/>
<% loops = loops + 1 %>
<% end %>
</form>
My javascript is as shown below:
document.getElementById("add_deal_button").addEventListener("click", function () {
var buttons = $('.choice');
var chart = $('#analytics_line').highcharts();
buttons.each(function () {
var currentBox = $(this);
var isChecked = currentBox.is(':checked');
var wasChecked = currentBox.data("wasChecked");
var choice = $(this).val();
<% loops = 0 %>
<% while loops < num_of_expired_deals %>
var title = "<%= raw #deals_daily_count[position][loops]%>"
if (choice == title) {
<% title_of_deal = #deals_daily_count[position][loops].to_s%>
}
<% loops = loops + 1 %>
<% end %>
<% merchant_id_position = #deals_daily_count.size - 1 %>
<% merchant_id = #deals_daily_count[merchant_id_position] %>
<%= raw data = DealAnalyticService.set_analytics_for_line_graph(merchant_id, title_of_deal, Date.today.beginning_of_month, Date.today) %>
if (!wasChecked && isChecked) {
var series = chart.addSeries({
name: "<%= data[0][0]%>" + " view count",
pointStart: <%= data[0][1] %>,
pointInterval: 24 * 3600 * 1000,
data: <%= data[0][2] %>,
visible: true
});
currentBox.data("series", series);
var series2 = chart.addSeries({
name: "<%= data[0][0]%>" + " redemption count",
pointStart: <%= data[0][1] %>,
pointInterval: 24 * 3600 * 1000,
data: <%= data[0][3] %>,
visible: true
});
currentBox.data("series2", series2);
}
if (wasChecked && !isChecked) {
var series = currentBox.data("series");
series.remove();
var series2 = currentBox.data("series2");
series2.remove();
}
if (isChecked) {
currentBox.data("wasChecked", true);
}
else {
currentBox.data("wasChecked", false);
}
});
});
To explain what I'm doing, I am actually using HighCharts and am trying to populate the data into a series and add it to my chart when checkbox is ticked. When it isn't tick, I will remove it from my graph.
The removing and adding part is working perfectly. Only issue is that when adding a graph, apparently
buttons.each(function (){}
is not working properly. It does not go iterate through every single checkbox and give me the value of that particular checkbox. Instead, I believe it returned me all values of the checkbox. This results in regardless which checkbox is checked, only the last value is used since it goes through my while loop.
I have tried using ("input:checkbox").each(function() {} but it gives me the same result.
I've also tried using isChecked to determine whether to pass the value into choice or pass null but it does not work as well
I hope that someone can explain to me why is this the issue as I've been trying several methods with no success for hours.
Thank you!

Related

Ruby on Rails options_for_select onchange to call a Javascript function?

How do you setup a select element to change the maximum value of a number field element on a change of value?
I want to change the max value of the passenger number field when the flight ID is changed.
This is my code so far. As you can see, I added the onchange at the end of the select layout.
<div class="field">
<%= form.label :flight_id %>
<%= form.select :flight_id, options_for_select(Flight.all.map {|flight| [flight.name, flight.id]}, form.object.id), onchange: 'getMaxCapacity()' %>
</div>
<div class="field">
<% qty = #reservation.passengers %>
<%= form.label :passengers %>
<%= form.number_field :passengers, :id => 'passengers', min: 1, onchange: "calculateTotalPrice()", oninput: "calculateTotalPrice()" %>
</div>
My Javascript function getMaxCapacity() never gets entered. In the function I am setting the max value of the 'passengers' number field to the capacity variable.
<script type="text/javascript">
var capacity = {
<% Flight.all.each do |flight| %>
'<%= flight.id %>': <%= flight.capacity %>,
<% end %>
};
function getMaxCapacity() {
document.getElementById('passengers').max = capacity;
}
var costs = {
<% Flight.all.each do |flight| %>
'<%= flight.id %>': <%= flight.cost %>,
<% end %>
};
function calculateTotalPrice() {
var price = costs[document.getElementById('reservation_flight_id').value];
document.getElementById('cost').value = document.getElementById('passengers').value * price;
}
</script>
The signature of the FormBuilder#select looks like this:
select(method, choices = nil, options = {}, html_options = {}, &block)
This means html_options are the fourth parameter. Because you do not have any options for the select method you need to pass an empty hash as a third parameter.
<%= form.select(
:flight_id,
options_for_select(Flight.all.map {|flight| [flight.name, flight.id]}, form.object.id),
{}, # empty options
onchange: 'getMaxCapacity()' %>. # here the HTML options

Rails countdown characters - replace script tag in view

In my Rails 5 app I'm trying to display the amount of characters remaining for the following text area in the view with tag:
<%= form_for #note, :url => registrant_notes_path(#registrant) do |f| %>
<div>
<%= f.text_area :body, maxlength: 1000, style: 'width:100%;', id: "review_text" %>
<%= f.submit "Save", class: "btn btn-primary" %>
</div>
<% end %>
<script>
$(document).ready(function() {
var review_text = $("#review_text");
var counter = $("#counter");
var max_length = counter.data("maximum-length");
counter.text(max_length - review_text.val().length);
review_text.keyup(function() {
counter.text(max_length - $(this).val().length);
});
});
</script>
How to get rid of this script tag and move it to some js file? I created new file under app/assets/javascripts/notes.js with below code:
$(document).on('turbolinks:load', function() {
var review_text = $("#review_text");
var counter = $("#counter");
var max_length = counter.data("maximum-length");
counter.text(max_length - review_text.val().length);
review_text.keyup(function() {
counter.text(max_length - $(this).val().length);
});
});
but then this JS code stops working - it stops counting down. Should I add this notes.js somewhere or am I missed something else?

Rails passing value to hidden field using javascript

I have an array structured as follows:
<% #locations = [['Town 1',2],['Town 2',2]...] %>
That I pass through an options_for_select tag that passes the shows the town name correctly and passes the id when submitted which is great. But, what I want to do is pass the town name (key?) as well to display on the results page as well. I understand the best method is to use a hidden_field_tag with javascript to pass the value through, but all I can pass is the id value, not the town name value.
Form
<%= form_tag(results_path, method: :post) do %>
<%= select_tag :location, options_for_select(#locations) %>
<%= hidden_field_tag(:location_name, value = nil, html_options = {id: 'locationName'}) %>
<%= submit_tag 'Submit' %>
<% end %>
Javascript
$('#location').change(function(){
var input = document.getElementById("location");
var site = document.getElementById("locationName");
site.value = input.value;
})
As you're using jquery:
$('#location').change(function(){
var locationName = $("#location option:selected").text(); # this will return the selected option text e.g. location name
$("#locationName").val(locationName);
})
Hope it works!

JQuery How to hide/show dynamic number of divs all with unique id

I am not very good with JQuery but I am trying to learn. I am rendering number of "Milestone" number fields based on how many "Events" are defined in the database. So for 2 events there will be 2 number fields. What I am having trouble doing is hiding all the fields and only displaying one based on the selection in the "Event" select field. Here are the code snippets:
<div>
<%= f.label "Event" %>
<%= f.select(:event, options_for_select(get_events),{}, { :class => 'form-control', :id => 'event'})%>
<%if any_errors(#attendance_policy, :event) != nil%>
<%= any_errors(#attendance_policy, :event) %>
<%end%>
</div>
.....
<% Event.all.each do |event| %>
<div id='<%=event.event_name%>' >
<%= f.label "Absence Milestone(Make dynamic with selected event)"+event.event_name %>
<%= f.number_field :absence_milestone, in: 0..event.absence_max.to_i, class: 'form-control' %>
<%if any_errors(#attendance_policy, :absence_milestone) != nil%>
<%= any_errors(#attendance_policy, :absence_milestone) %>
<%end%>
</div>
<%end%>
Heres my pitiful attempt at JQuery:
$(document).ready(function() {
$("select#event").bind("change", function() {
var selected = $("select#event").text();
$("div#"+selected).show();
})
})
I understand I have to capture all the divs but I dont know how honestly... You cannot pass ruby arguments to JQuery... The hide them all, Capture text from event selector and only show one which id matches what is selected in the selector..
UPDATE
Working code:
Ruby portion not much changed other than me setting class of the div as 'wipe'.
<% Event.all.each do |event| %>
<div id="<%= event.event_name%>" class="wipe">
<%= f.label "Absence Milestone" %>
<%= f.number_field :absence_milestone, in: 0..event.absence_max.to_i, class: 'form-control' %>
<%if any_errors(#attendance_policy, :absence_milestone) != nil%>
<%= any_errors(#attendance_policy, :absence_milestone) %>
<%end%>
</div>
<%end%>
Here is updated jQuery. I have found another error while testing where my validator would complain that field cannot be blank even though I have entered a value in. Reason behind was that all other hidden fields did not have anything typed in. I updated jQuery to update ALL the hidden fields with value typed in the shown one on focus lost event.
jQuery Working(Might be messy):
$(document).ready(function() {
$("[class='wipe']").hide();
var selected = $("select#event").find("option:selected").text();
$("[id='" + selected + "']").show();
$("[id='" + selected + "']").on('focusout', function() {
var input = $(this).find("input").val();
$('input[type=number]').val(input)
})
$("select#event").on('change', function() {
$("[class='wipe']").hide();
var selected = $(this).find("option:selected").text();
$("[id='" + selected + "']").show();
$("[id='" + selected + "']").on('focusout', function() {
var input = $(this).find("input").val();
$('input[type=number]').val(input)
})
});
You're close. You should be using .change() instead of .bind() and you need to find the text of the selected option:
$(document).ready(function() {
$("select#event").change(function() {
var selected = $(this).find("option:selected").text();
$("div#"+selected).show();
})
})
.bind() is deprecated
FIDDLE
If I understood right .. You can't do that using Ids Id is unique so you need to use Classes
$("div."+selected)
you can use this code
$(document).ready(function() {
$('div.hidden').hide();
$("select#event").on('change',function() {
var selected = $(this).val();
$('div.hidden').hide();
$('div.'+selected).show()
});
});
you can check demo
DEMO

Jquery/javascript flash function for multiple elements

Check out this piece of code:
var shipping = $('#shipping_cell');
var total = $('#total_cell');
flash_cell(shipping);
flash_chell(total);
function flash_cell(target){
var background = target.css('backgroundColor');
target.stop().css("background-color", "#ac4341").animate({ backgroundColor: background}, 1500);
}
When I run this code, only the #shipping cell flashes.
If I switch the lines flash_cell(shipping); and flash_cell(total); around, neither one flashes.
Why don't they both flash?
Edit - here is my html
<td id = 'total_cell'><%= view_in_preferred_currency(#order.total) %></td>
<td id = "shipping_cell">
<% if #order.free_shipping? or #order.collection? %>
<%= view_in_preferred_currency(0) %>
<% else %>
<%= view_in_preferred_currency(#order.shipping_option.price) %>
<% end %>
</td>
Fix your typo:
flash_chell(total) to flash_cell(total)

Categories