Getting the total sum of radial button values - javascript

I am trying to get the sum of all radial buttons selected. There are three groups of three in total with a possibility of three checked. These are created by the Angular ng-repeat that you will see in the index page.
I have lurked through many posts saying that they have found a way to do this, but I still don't get the output that I need. I know that the jQuery is running because I tested that. So I don't know what is going in.
Please see if you can spot or suppose what is going on. Thank you The code looks horrendous and uneven but this is because the box keeps screwing the hierarchy of my code.
<!DOCTYPE html>
<html>
<head>
<title>Cruiseline</title>
<%= javascript_include_tag 'application'%>
<%= stylesheet_link_tag 'application', media: 'all'%>
<%= csrf_meta_tags %>
<script>
$( document ).ready(function() {
$(".all_aboard").click(".radial_input", function() {
var total = 0;
$("input[type=radio]:checked").each(function() {
total += parseFloat($(this).val());
});
$(".totalSum").val(total);
});
});
</script>
</head>
<body>
<%= yield %>
</body>
</html>
<h1 class="title">Choose Your Sailings <span class="pick_one">(Pick one for each box)</span></h1>
<div class="all_aboard" ng-app="app">
<div ng-controller="CruisesController">
<div ng-repeat="cruise in cruises">
<div class="panel panel-default">
<div class="panel-body">
<div ng-controller="SailingsController">
<div ng-repeat="sail in sailings ">
<div ng-if="sail.cruise_id == cruise.id">
<div>
<img src="{{ sail.main_image }}" class="cruise_picture"/>
<img><%= image_tag "lowest_price_tag.png", class: "lowest_price_tag"%> <img/>
</div>
<div class="cruise_details">{{cruise.name}}-{{cruise.ship_name}}</div>
<h1 class="sailing_title">{{ sail.name }}</h1>
<div ng-controller="SailingOptionsController">
<div class="option_box" ng-repeat="soption in sailing_options">
<div ng-if="soption.sailing_id == sail.id" >
<div class="radio">
<input class="radial_input" id="soption{{soption.id}}" type="radio" name="cruisePrice{{sail.id}}" data-price="{{soption.price}}">
<div class="date">{{ soption.date}}</div>
<div class="price">${{ soption.price}}</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<br/>
<br/>
<div class="divider"></div>
<div>
<h1 class="you_selected_total">You Selected Sailings Total</h1>
<input style="color:red;" type="text" class="totalSum" value="" readonly="readonly">
</div>

try this
I updated answer now try
$(".all_aboard").on("click",".radial_input", function() {
var total = 0;
$(document).find("input[type=radio]:checked").each(function() {
total += parseFloat($(this).parent().find('.price').text());
});
$(".totalSum").val(total);
});

I can see couple of things in your code.
First, if you are using jQuery to make things work, you should wrap it up in a $(document).ready(function() {}); like below.
$(document).ready(function () {
$("input[type='radio']").click(function() {
var total = 0;
$("input[type=radio]:checked").each(function() {
total += parseFloat($(this).val());
});
$(".totalSum").val(total);
});
});
If you are planning to add more radio buttons using code, then you should consider using jQuery 'on' to bind events.
Next, you should use check boxes instead of radio buttons if you are trying to enable multiple select (I am assuming you are, since you are looking to get a total).
Next, try and minimize direct use of jQuery when developing your angular applications: it can lead to lot of confusions and unwanted scenarios like your angular functions not getting executed, or your angular variables not getting updated.
Finally, take a look at the below fiddle and see if it fits your solution
JSFiddle: Update Price when Checked

Related

Ruby Checkbox with Icon now showing/hiding a div on toggle

Forgive me for asking this question but I have been pulling my hair trying to fix this but I cannot understand where I am messing up. I have checked many answers on SO which recommend using attr or props in Jquery which did not work for me so I think I might be making some other problem.
I have ruby code where I have an icon. When I click on this icon, I want to show/hide another div.
My ROR code:
<div class="choice <%= 'active' if listing.payment_term_shortterm == 'on' %>" data-toggle="wizard-checkbox">
<%= form.check_box :payment_term_shortterm, id: "payment_term_shortterm_test" %>
<div class="card card-checkboxes card-hover-effect">
<i class="ti-home"></i>
<p>Small Time</p>
</div>
</div>
This above thing creates this icon in my website as follows:
I just want that if Small Time is clicked it shows another div. My Jquery so far:
$(function () {
$("#payment_term_shortterm_test").click(function () {
if ($(this).is(":checked")) {
$("#SmallTimeShow").show();
} else {
$("#SmallTimeShow").hide();
}
});
});
And this jquery is supposed to show following div:
<div id="SmallTimeShow" style="display: none;">
<div class="form-group">
<div class="row">
<div class="col-md-8 col-md-offset-1">
<p> Hi Loan for Small time.</p>
</div>
</div>
</div>
</div>
I have tried many things, such as using props or attr in jquery but it also did not work.
EDIT
THis is what appears in the browser inspect element:
You can try with display 'block' and display 'none' as I mentioned below:
$('#payment_term_shortterm_test').change(function() {
if($(this).is(":checked")) {
$("#SmallTimeShow").css('display','block');
}
else{
$("#SmallTimeShow").css('display','none');
}
});

How to show element only if other element contains something using jQuery?

My guess is what I want to achieve should be easy, but due to my lack of knowledge of front-end development, I cannot manage to solve issue. Have a page that works with AJAX-filters that users can select. Filters that are currently applied show up within <div> with id=current-filters.
HTML looks like this:
<div id="current-filters-box">
<div style="margin-bottom: 15px">
<strong>Current filters:</strong>
<div id="current-filters">
<!-- here every single applied filter is displayed -->
</div>
</div>
</div>
Need to hide the the entire DIV current-filters-box in case no filter is applied.
The page uses a Javascript file, bundle.js which is massive, but contains the following line:
s=document.getElementById("current-filters")
Therefore tried the following if-statement to hide the DIV:
if(s.length<1)$('#current-filters-box').hide()
and
if(s=0)$('#current-filters-box').hide()
But this does not seem to have any effect. Can someone tell, what I did wrong?
Demo of page can be found here
EDIT: this is what the HTML looks like when filters are applied:
<div id="current-filters-box">
<div style="margin-bottom: 15px">
<strong>Current filters:</strong>
<div id="current-filters">
<div class="badge-search-public">
<strong>Humanities & Languages</strong> <span class="x" data-property="disciplines" data-value="4" onclick="filter.removeFilter(this)">×</span>
</div>
<div class="badge-search-public">
<strong>January</strong> <span class="x" data-property="months" data-value="1" onclick="filter.removeFilter(this)">×</span>
</div>
</div>
</div>
Both of your conditions are incorrect or I would say they are not doing what you think they do.
s.length will always prints undefined so instead of s.length<1 you could use s.children.length
and the second one is not a condition rather it is an assignment
s==0 // condition
s=0 //assignment
the correct condition for your requirement would be
if(s.children.length<1){
I have assigned snippets for illustration.
Without filters
s = document.getElementById("current-filters")
console.log(s.children.length);
if (s.children.length < 1) {
$('#current-filters-box').hide(1000)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="current-filters-box">
filter box
<div style="margin-bottom: 15px">
<strong>Current filters:</strong>
<div id="current-filters">
<!-- here every single applied filter is displayed -->
</div>
</div>
</div>
Without filters
s = document.getElementById("current-filters")
console.log(s.children.length);
if (s.children.length < 1) {
$('#current-filters-box').hide(1000)
}
<div id="current-filters-box">
<div style="margin-bottom: 15px">
<strong>Current filters:</strong>
<div id="current-filters">
<div class="badge-search-public">
<strong>Humanities & Languages</strong> <span class="x" data-property="disciplines" data-value="4" onclick="filter.removeFilter(this)">×</span>
</div>
<div class="badge-search-public">
<strong>January</strong> <span class="x" data-property="months" data-value="1" onclick="filter.removeFilter(this)">×</span>
</div>
</div>
</div>
Try this .
if( $('#current-filters').is(':empty') ) {
$('#current-filters-box').hide()// or $('#current-filters-box').css("display","none")
}
You are performing an assignment, try..
if (s.children.length)
Using vanilla JavaScript, you can check if the current-filters div is empty or not and toggle the parent div current-filters-box like this:
s= document.getElementById("current-filters");
t= document.getElementById("current-filters-box");
if(s.children.length<1) {
t.style.display = 'none';
// t.style.visibility= 'hidden'; <<-- use this if you want the div to be hidden but maintain space
}
else {
t.style.display = 'block';
// t.style.visibility= 'visible'; <<-- use this if you used visibility in the if statement above
}
You can achieve this by adding your own variable which counts or maintains your applied filters, e.g.
var applied_filter_count = 0;
at every time filter is applied
applied_filter_count++;
if(applied_filter_count) {
$('#current-filters-box').show()
}
and at every time filter is removed
applied_filter_count--;
if(!applied_filter_count) {
$('#current-filters-box').hide()
}
and by default current-filters-box should be display:none

ASP custom control - how to get children in JS/jQuery

In my app I have a lot of the same HTML blocks so I don't want to repeat them.
I found out that I can select a block of HTML code and select Extract to User Control option.
It creates an .ascx file with content like this:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="div_field.ascx.cs" Inherits="Obipoly.layout.div_field" %>
<div class="field">
<div class="status_bar">
<div class="hotel_placeholder">
<div class="house_placeholder"></div>
<div class="house_placeholder"></div>
<div class="house_placeholder"></div>
<div class="house_placeholder"></div>
</div>
<div class="players_container">
<div class="player_placeholder"></div>
<div class="player_placeholder"></div>
<div class="player_placeholder"></div>
<div class="player_placeholder"></div>
</div>
</div>
<div class="field_name"></div>
<div class="field_image"></div>
<div class="field_price"></div>
<div class="field_owner"></div>
</div>
I can now use this block in my .aspx file:
<uc1:div_field runat="server" ID="field39" />
Now I need to iterate through my elements (id=field0, id=field1,...) and change some data.
How can I get a reference to each element and find each child in it?
I tried:
for (var i = 0; i < 40; ++i) {
var fieldId = "#field" + i.toString();
var field = $(fieldId);
alert(field); //displays object Object
field.find(".field_name").append($("<p/>", {
text: i
}))
}
But nothing happens. I'm not sure if I can do
var field = $(fieldId);
as if my element were an ordinary html tag.
What if want to find an element which shares the same class with others, e.g. I want to get third <div> with player_placeholder class and give it a unique id?
Or the only way is to create all the elements with JavaScript at runtime?
Thanks.
PS. The reason I can't get any of my fields is that in my DOM I have only body of my control. I thought I would have:
<div id="field20">
<div class="field">
...
</div>
</div>
But actually it is:
<div class="field">
...
</div>
The problem here is that if you were to inspect the ID that asp.net created for you it will not be field39 it would be some custom one, you can however override this behaviour by using ClientIDMode
<uc1:div_field runat="server" ID="field39" ClientIDMode="static" />

$().next() returning the same element multiple times

I tried to name the title as best I could. A little difficult for me to explain.
I'm having an issue with some code I'm writing (which runs in a widget on my wordpress site.) What I've written here emulates this issue. Just fyi I'm very new to jquery, JS, etc.
What I'm trying to do is set the variable "thumb" to the element after "widget-code". It works, however it's only finding that element ("thumb-class") in "wordpress-post1"
The console output is:
wordpress-post1
wordpress-post1
wordpress-post1
But it should be:
wordpress-post1
wordpress-post2
wordpress-post3
This is the actual code
<div class="wordpress-post1">
<div id="widget-code">
<script>
$(document).ready(function(){
var thumb = $("#widget-code").next();
console.log(thumb[0].parentElement.className);
});
</script>
</div>
<div class="thumb-class">
</div>
</div>
<div class="wordpress-post2">
<div id="widget-code">
<script>
$(document).ready(function(){
var thumb = $("#widget-code").next();
console.log(thumb[0].parentElement.className);
});
</script>
</div>
<div class="thumb-class">
</div>
</div>
<div class="wordpress-post3">
<div id="widget-code">
<script>
$(document).ready(function(){
var thumb = $("#widget-code").next();
console.log(thumb[0].parentElement.className);
});
</script>
</div>
<div class="thumb-class">
</div>
</div>
I'm going to try and clarify a little more:
This code is placed in an html widget which the wordpress theme I'm using provides. It hooks into each post. This is the only place I can put code, and this is the only code I've written. (I haven't altered the theme's files in any way.)
I have no control over the name of the classes or IDs. And they're dynamic. An unlimited number of posts could exist. Therefore I can't hardcode anything.
In order for this code to work correctly it'll need to find the sibling of the "widget-code" element in only the post it's running from.
This is the link to the code on JSFiddle: http://jsfiddle.net/pattnvy3/
Would appreciate any help on the matter.
If you want a nasty hack, try
<div class="wordpress-post1">
<div id="widget-code">
<script>
$(document).ready(function(){
var c = window['widget-code-counter'] || 0;
window['widget-code-counter'] = ++c;
var className = 'wordpress-post' + c;
console.log(className);
});
</script>
</div>
<div class="thumb-class">
</div>
</div>
Demo: Fiddle
It will give the container class wordpress-post1, then you can use it to find any of the descendant element.
As per the immediate comments, it is invalid markup to use an id for multiple elements. That said, changing your id to a class such that:
<div class="wordpress-post[some-number-here]">
<div class="widget-code">
</div>
<div class="thumb-class">
</div>
</div>
would allow you to to a jQuery selector like so:
$('.widget-code').each(function (){
var thumb = $(this).next();
console.log(thumb[0].parentElement.className);
});
However, if I may make a recommendation, I would say that you tag each of your wordpress-post divs with the class "wordpress-post" and then have a more specific id which is the value you want to print.
Then it would look like this:
<div id="wordpress-post[some-number-here]" class="wordpress-post">
<div class="widget-code">
</div>
<div class="thumb-class">
</div>
</div>
and your javascript like this (with jQuery):
$('.widget-code').each(function (){
var post = $(this).closest('.wordpress-post');
console.log(post.attr('id'));
});
or even simpler:
$('.wordpress-post').each(function (){
console.log($(this).attr('id'));
});
depending on the needs you have. If you have any questions as to what you need, feel free to comment and I will get back to you as soon as I can.
A pure javascript method:
This is just a workaround since you have no control over ids or classes, this will target all div elements on the page, loop through them and search for any that contains wordpress-post in the class name.
window.onload=function(){
var posts=document.getElementsByTagName('div');
for(var i=0; i<posts.length; i++){
if(posts[i].className.indexOf("wordpress-post")> -1){
console.log(posts[i].className);
//Snippet Use
alert(posts[i].className);
}
}}
<div class="wordpress-post1">
<div id="widget-code"></div>
<div class="thumb-class"></div>
</div>
<div class="wordpress-post2">
<div id="widget-code"></div>
<div class="thumb-class"></div>
</div>
<div class="wordpress-post3">
<div id="widget-code"></div>
<div class="thumb-class"></div>
</div>
If you have any questions, please leave a comment below and I will get back to you as soon as possible.
I hope this helps. Happy coding!
This can help if you want to have multiple IDs:
$(document).ready(function(){
$("[id^=widget-code]").each(function(){
console.log(this.parentElement.className);
});
});
But, still multiple same Ids are not recommended.
FIDDLE
Update: Declare a global variable var i=0; and keep increment it like :
<div class="wordpress-post1">
<div id="widget-code">
<script>
var i=0;
$(document).ready(function(){
var thumb = $("[id^=widget-code]").next();
console.log(thumb[i++].parentElement.className);
});
</script>
</div>
<div class="thumb-class">
</div>
</div>
<div class="wordpress-post2">
<div id="widget-code">
<script>
$(document).ready(function(){
var thumb = $("[id^=widget-code]").next();
console.log(thumb[i++].parentElement.className);
});
</script>
</div>
<div class="thumb-class">
</div>
</div>
<div class="wordpress-post3">
<div id="widget-code">
<script>
$(document).ready(function(){
var thumb = $("[id^=widget-code]").next();
console.log(thumb[i++].parentElement.className);
});
</script>
</div>
<div class="thumb-class">
</div>
</div>
DEMO

Unable to use $.after() to close a div tag

This problem is best illustrated by example:
http://jsbin.com/lavonexuse
The desired effect is for clicking "Insert Row" to insert a full-width row after the indicated column (indicated by the class .insertion-point). The problem I'm running into is that instead of closing the current row first, and starting a new one, it just embeds a new row within the main row.
How do I close out the current row after any given column, make a new row, close that one, then resume showing the "data" columns?
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-4 item">
Data
</div>
<div class="col-sm-4 item insertion-point">
Data
</div>
<div class="col-sm-4 item">
Data
</div>
<div class="col-sm-4 item">
Data
</div>
<div class="col-sm-4 item">
Data
</div>
<div class="col-sm-4 item">
Data
</div>
</div>
</div>
<button class="btn btn-primary insert-row">Insert Row</button>
</body>
</html>
CSS:
.item {
border: 1px solid #f00;
}
.pane {
background: #999;
height: 100px;
}
JavaScript:
$('.insert-row').on('click', function() {
code = '</div><!--end row--><div class="row"><div class="col-sm-12 pane"></div></div>';
$('.insertion-point').after(code);
});
EDIT:
The code string above probably should end with <div class="row"> to re-open the row. But I tried that and it still doesn't work.
The problem here is that visually it looks like my solution works. Though in reality, it's creating bad HTML.
Further explanation (I think this is hard to explain). Here is what's happening, and this is NOT what I want:
I need that inserted row to be at the same level as the row it was erroneously inserted into.
Desired HTML after jQuery manipulation
<div class="container">
<div class="row">
<div class="col-sm-4 item">
Data
</div>
<div class="col-sm-4 item insertion-point">
Data
</div>
</div>
<div class="row">
<div class="col-sm-12 pane"></div>
</div>
<div class="row">
<div class="col-sm-4 item">
Data
</div>
<div class="col-sm-4 item">
Data
</div>
<div class="col-sm-4 item">
Data
</div>
<div class="col-sm-4 item">
Data
</div>
</div>
</div>
Further Ramblings
Maybe, since this is Bootstrap, there's some way I can use the grid system to have the same effect.
The code below should resolve your issue. Check out the code snippet and demo:
$('.insert-row').on('click', function() {
var row = $('<div/>',{class:"row"}),
code = '<!--end row--><div class="row"><div class="col-sm-12 pane">New</div></div>',
rest = $('.insertion-point').nextAll(),
dest = $('.insertion-point').closest('.row');
dest.after( row.append( rest ) ).after( code );
});
<script src="//code.jquery.com/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<div class="container">
<div class="row">
<div class="col-sm-4 item">
Data
</div>
<div class="col-sm-4 item insertion-point">
Data
</div>
<div class="col-sm-4 item">
Data
</div>
<div class="col-sm-4 item">
Data
</div>
<div class="col-sm-4 item">
Data
</div>
<div class="col-sm-4 item">
Data
</div>
</div>
</div>
<button class="btn btn-primary insert-row">Insert Row</button>
i worked out this four you: JsFiddle
$(document).ready(function() {
var firstRow = $('.row');
$('.insert-row').on('click', function() {
var code = $('<div/>', {clas: 'row'}).append($('<div/>', {class: "col-sm-12 pane"})),
row = $('<div/>', {class: 'row'}),
items = $('.insertion-point').nextAll();
row.append(items);
firstRow.after(row);
firstRow.after(code);
});
});
Update:
after seen the nextAll function by jQuery .. this will be much faster:
updated fiddle
I think what you need is appendTo which will append html onto the specified tag. In this case you want to append a div onto your row.
http://api.jquery.com/appendto/
Just get rid of the closing tag in the code variable and your code will work and be well formed
code = '</div><!--end row--><div class="row"><div class="col-sm-12 pane"></div></div>';
should be
code = '<div class="row"><div class="col-sm-12 pane"></div></div>';
Also you need to insert rows after / before other rows like so
$('.insert-row').on('click', function() {
code = '<div class="row"><div class="col-sm-12 pane"></div></div>';
$('.insertion-point').closest(".row").after(code);
});
The above code finds where you want to insert (which I changed to be an id selector since you want to insert after one unique element). However you want to find the closest parent element (or this one) that is a row so that you insert a row after that row. This way you can choose a row or a column to insert after and it will always insert a row after the closest row properly.
Lucky for you browsers are very forgiving when it comes to syntax errors in HTML. They will remove the initial closing tag (which is unnecessary) and use the rest of your HTML. But some browser may behave differently and that is what you have to be careful of.
You need to add a new row after the first by removing the elements after the insertion point and including them in the new row.
You can't treat the DOM like a text editor when inserting html.
$('.insert-row').on('click', function() {
var $insertEL=$('.insertion-point');
var code = '<div class="row"><div class="col-sm-12 pane"></div></div>';
/* create new row and append all siblings after insertion point element*/
var $newRow=$(code).append($insertEL.nextAll());
/* add new row to DOM*/
$insertEL.closest('.row').after($newRow);
});
DEMO
Got it!
Layout solved by using Bootstrap grid, very little jQuery DOM manipulation. I don't know why I didn't think of this earlier. Sheesh. I've been coding for hours non-stop, my brain is fried.
Solution: http://jsbin.com/zopiquzore
This is correct, yes?

Categories

Resources