jQuery - Total and extra divs not showing? - javascript

i am trying to show the total amount of selected persons, and also add that number of extra divs in the form
This is me code: fiddle , but the total amount of persons is not showing also the extra divs are not working.
This is an example how it should be like : fiddle
What is wrong? And how can i make this work? Thanks!
This is my JS
$(document).ready(function(){
var sum = 0;
$(document).on('change', 'div select',function(){
sum = 0;
$('div select').each(function(){
var thisVal = parseInt($(this).val());
sum += thisVal;
});
$('#person-total').text(sum);
// you can use here
// remove all divs
$('div[class^="passenger"]').remove();
// to show divs depending on number of persons
for(var i = 1 ; i <= sum ; i++){
$('body').append('<div class="passenger'+i+'"><label for="passenger_name">Passenger '+i+'</label><input name="passenger_name_'+i+'" type="text" id="passenger_name" placeholder="FIRSTNAME"><input name="passenger_lname_'+i+'" type="text" id="passenger_lname" placeholder="LASTNAME"><input name="passenger_age_'+i+'" type="text" id="passenger_age" placeholder="AGE"></div>');
}
});
});
I found the problem i tink, its calculating al selected options., but how can i change this :
$(document).on('change', 'div select',function(){
sum = 0;
$('div select').each(function(){
var thisVal = parseInt($(this).val());
sum += thisVal;
});
Special for working for 1 div ?

The problem here is that your "choose a trip" drop down matches the selector 'div select', so it is included in the .each() loop. So when you call
parseInt($(this).val());
You end up with NaN which stands for "Not a Number".
I added a class of "count-select" to each of the select elements that should be included in this function, and modified the JavaScript as follows:
JS
$(document).ready(function () {
var sum = 0;
$(document).on('change', '.count-select', function () {
sum = 0;
$('.count-select').each(function () {
var thisVal = parseInt($(this).val());
sum += thisVal;
});
$('#person-total').text(sum);
// you can use here
// remove all divs
$('div[class^="passenger"]').remove();
// to show divs depending on number of persons
for (var i = 1; i <= sum; i++) {
$('body').append('<div class="passenger' + i + '"><label for="passenger_name">Passenger ' + i + '</label><input name="passenger_name_' + i + '" type="text" id="passenger_name" placeholder="FIRSTNAME"><input name="passenger_lname_' + i + '" type="text" id="passenger_lname" placeholder="LASTNAME"><input name="passenger_age_' + i + '" type="text" id="passenger_age" placeholder="AGE"></div>');
}
});
});
Here's the updated fiddle: https://jsfiddle.net/voveson/9rspxhjy/2/
Hope it helps!

Related

Having trouble calculating the value of a list of classes in Javascript

I'm trying to add all the values from the class "q-total" But I can't get it to work. Here's the code:
$(document).on("change", ".row-inputs", function(){
var total = 0;
var price = 0;
var multi = 0;
$('.q-quantity', this).each(function(){
multi = $(this).val();
})
$(".q-price", this).each(function(){
price += +$(this).val() * multi;
})
$(".q-total", this).val(price);
for (var i = 0; i < $(".q-total").length; i++) {
// total = 0;
// console.log($(".q-total", this).val() )
total += parseInt($(".q-total", this).val());
}
console.log("Total " + total)
})
Below is the class code I use to add new rows to the html. In case this might help to figure out why the above code is not working.
var counter = 1;
var limit = 10;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + "
inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.className = "row-inputs";
newdiv.innerHTML = "<input type='text' name=''
placeholder='product name' class='q-product-name'> " +
"<input type='number' name='' placeholder='0' class='q-quantity'
value=1> " +
"<input type='text' name='' placeholder='price' class='q-price'> "
+
"<input type='text' name='' placeholder='price' class='q-total'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
Thank you
Your loop is incorrect:
Change
for (var i = 0; i < $(".q-total").length; i++) {
// total = 0;
// console.log($(".q-total", this).val() )
total += parseInt($(".q-total", this).val());
}
To
$(".q-total").each(function(){
total += +$(this).val();
})
In the original for loop you never iterate over the values, you always take $(this).val(). Not sure why you varied from your .each() approach you've used everywhere else, but that is your fix.
To explain further, using your example of add rows with prices of 3,4,5. The first time through (1st row), you have one element in the jQuery collection, so total=0 becomes total += 3; Second row added and you have two elements, but only look at the value of the current row, so total=0 becomes total += 4 && total += 4 hence total=8; On third row change, there are three elements, to total = 15 ( 3 * 5);

Change data property using checkbox from false to true using jQuery

I have created list of items in a table. I want to calculate the price of checked items, but can't figure out how to update the data property when a checkbox is checked/unchecked. I have included the code for generating the list and updating the price calculation.
$.each(shopList, function (i, elem) {
var item = elem.item;
var link = elem.link;
var user = elem.user;
var price = elem.price;
var priority = elem.priority;
$(".listItems").append(
'<tr class="items" data-priority="' + priority + '">' +
'<td><input type="checkbox" class="priority"' + ((priority) ? 'checked' : '') + ' /></td>' +
'<td>' + '' + item + '' + '</td>' +
'<td>' + user + '</td>' +
'<td class="price">' + price + '</td>' +
'<td><button class="btn btn-default deleteItem">Del </button></td>' +
'</tr>'
);
});
And the code to update the price:
function updatePriority(){
sumPriority = 0;
$('tr.items[data-priority=true] .price').each(function () {
var total = $(this).text();
if (!isNaN(total) || total.length != 0) {
sumPriority += parseFloat(total);
};
});
$('.totalPriority').html(sumPriority.toFixed(2));
};
When the page renders it has checked and unchecked items and everything works that way at first, but not when a change is made.
How can I update the data-property true/false in the DOM?
Do not use data-property but just use the Checkbox :checked status
Instead of looping over the [data-priority=true] checkboxes you can loop over the checked checkboxes instead, and use parent().find('.price') to find the correct price labels.
function updatePriority(){
sumPriority = 0;
$('.priority:checked').each(function () {
var priceElement = $(this).parent().parent().find('.price');
var total = priceElement.text();
if (!isNaN(total) || total.length != 0) {
sumPriority += parseFloat(total);
};
});
$('.totalPriority').html(sumPriority.toFixed(2));
};
How can I update the data-property true/false in the DOM?
If you really want to keep your code as it is and only update the data-priority attribute when you change a checkbox you can implement change listeners on the checkboxes and change the parents attribute:
$('tr.items .price').change(function() {
if ($(this).is(":checked")) {
$(this).parent().parent().attr("data-priority",true);
}else{
$(this).parent().parent().attr("data-priority",false);
}
});
You can try this :
function updatePriority(){
sumPriority = 0;
$('.listItems tr td .priority').each(function () {
if ($(this).is(":checked"))
{
var price=$(this).parent().find('.price').text();
var total = price;
if (!isNaN(total) || total.length != 0) {
sumPriority += parseFloat(total);
};
}
});
$('.totalPriority').html(sumPriority.toFixed(2));
};

How to select multiple columns with JQuery to populate another control on page

I have a page with an HTML table and a select element. I want to use jQuery to extract two columns each row of the able, and add the columns as entries in the select list. For example, if my table is:
1 apple extra
2 banana extra
3 cherry extra
Then when the page loads I would like to add three labels to the select, one for each fruit name, with the corresponding values determined by the first column. I have unsuccessfully attempted to solve this at http://jsfiddle.net/dcodelli/7Ez9d/
My code:
$(document).ready
(
function()
{
var allindexes = $('#Fruits> tbody > tr > td:nthchild(1)').map(function(){
return $(this).text();
}).get();
var allnames = $('#Fruits> tbody > tr > td:nthchild(1)').map(function(){
return $(this).text();
}).get();
for (index = 0; index < a.length; ++index) {
$('#Preset').append('<option value = \"' + allindexes[index] +
'\">"' + allnames[index] + '</option>');
}
}
);
try
$(document).ready
(
$('table#Fruits > tbody > tr').each(function(trIndex) {
console.log ("tr");
var sText;
$(this).find('td').each (function(index, data) {
console.log(data);
if (index == 1) {
sText = $(this).html();
}
});
$('#PreSet').append("<option value='" +trIndex+ "'>" + sText + "</option>");
})
)
Many issues with your jsfiddle including wrong table name, wrong dropdown id.
Using your JSFiddle as a base (see JSFiddle: http://jsfiddle.net/dualspiral/6XdPm/)
$(document).ready(function () {
var allindexes = $('#Fruits > tbody > tr > td:nth-child(1)').map(function () {
return $(this).text();
}).get();
var allnames = $('#Fruits > tbody > tr > td:nth-child(2)').map(function () {
return $(this).text();
}).get();
for (index = 0; index < allindexes.length; ++index) {
$('#PreSet').append('<option value = "' + allindexes[index] + '">' + allnames[index] + '</option>');
}
});
You were using the wrong selector for nth-child (you missed out the hyphen), and in your for loop, you used the wrong variable (a.length instead of allindexes.length). Your JSFiddle also did not have the right ID for the dropdown (PreSet is not the same as Preset).

Get and loop through all Select Boxes in a Table with Jquery

i am new with jQuery.. i have a table with a number of boxes in it. I want to grab all the select boxes in the table and loop through them..
I am trying to create a function that does this and it looks like this:
function calculatePercentageTotal(tableName) {
var total = 0;
for (i = 0; i <= $("#" + tableName + ' select').length; i++) {
total += parseInt($("#" + tableName + ' select')[i].val());
}
return total;
}
It's not working though.. any ideas? thanks!
this should do it:
function calculatePercentageTotal(tableName) {
var total=0;
$('#'+tableName+' select').each(function(){
total+= +($(this).val());
});
return total;
}
$(document).ready(function(){
var total =0;
$("#calculatebtn").click( function(e){
$("select").each(function(){
total += parseInt($(this).val());
});
alert("total=" + total);
});
});
You need a button with id='calculatebtn'
Just use a selector to get the elements. I'm not sure which elements you are looking for. If what you are trying to do is to sum the values of the selected items in all the selects(dropdowns) then you can use this:
var mysum = 0;
$("#" + tableName.id + ' select').each(function(){
mysum += $(this).val() * 1;
});
alert("mysum = " + mysum.toString);
// Why **"$(this).val() * 1"** - .val() will return a string with the value selected
// * 1 will make it numeric.

Limit inserting the element to the page

I'm trying to limit inserting elements to the page:
<script type="text/javascript">
$(function() {
var i = 1;
//allow only 3 elements
if (i < 4) {
$('#add').click(function() {
var add_input = '<input type="file" />'
var add_link = 'Remove'
$('body').append('<p>' + add_input + add_link + '</p>');
});
i++;
}
$('.remove').live('click', function() {
$(this).parent('p').remove();
});
});
</script>
But I can still add element a lot more than 4.
You need to check your variable i within your event handler.
$('#add').click(function() {
if(i < 4){
var add_input = '<input type="file" />'
var add_link = 'Remove'
$('body').append('<p>' + add_input + add_link + '</p>');
i++;
}
});
And you should decrease i within your live() handler.
See a working example : http://jsfiddle.net/CtGgg/
You could count the number of elements already on the page and limit it that way. Personally, I like treating the DOM itself as the canonical representation of user state. If that's important to you, you could do something like the following, even though it's a little less performant:
$('#add').live('click', function (evt) {
if ($('input[type=file]').length < 4) {
$('body').append('<p><input type="file"> Remove</p>');
}
evt.preventDefault();
});

Categories