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

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.

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);

Limit items in ajax request

I am requesting data from a json to fill a table. I want to limit to 5 the request.
jQuery.getJSON("data/data.json", function(data) {
var table = $("table");
$.each(data, function(id, elem) {
table.append("<tr class='text-center'><td>" + elem.dato1 + "</td><td>" + elem.dato2 + "</td></tr>");
});
})
Or another option is to add boolean key "active" to the data and that it brings me the data items with the value = true. How do i do this?
You can use .slice() to filter the returned array down to just the first 5 elements.
data = data.slice(0, 5);
Just use a simple for loop.
var json_arr, limit;
limit = 5; // set limit to whatever you like
json_arr = JSON.parse(json_data);
for(var i = 0; i < limit; i++;) {
var this_item = json_arr[i];
table.append(this_item); // do your thing
}
The best limit you can implement is on your own controller (where you get your data from)
But if you don't have access/don't want to change, you can simple achive this by JavaScript:
var limit = 5; //your Limit
for(var i in data){
if(i > limit) break;
var elem = data[i];
table.append("<tr class='text-center'><td>" + elem.dato1 + "</td><td>" + elem.dato2 + "</td></tr>");
}

Getting undefined when trying to fetch an ID from a data attribute

I can't figure out why am I getting undefined when trying to console.outthe iUsedId variable from the code below.
Here I attatch the user id to data-iUserId.
var aUsers = [];
for( var i = 0; i < aUsers.length; i++ ){
$("#lblUsers").append('<tr><th scope="row">'+aUsers[i].id+'</th><td>'+aUsers[i].username+'</td><td>'+aUsers[i].firstName+'</td><td>'+aUsers[i].lastName+'</td><td>'+aUsers[i].email+'</td><td>'+"<span data-iUserId='"+aUsers[i].id+"'</span><input type='checkbox' id='chk_"+i+"'"+'</td></tr>');
}
And here I am trying to use the data from the data attribute, but in the console all I get is undefined.
$(document).ready(function() {
$("#remove").on("click", function() {
$('input:checked').each(function() {
$(this).closest('tr').remove();
var iUserId = $(this).attr('data-iUserId');
console.log(iUserId);
for (var i = 0; i < aUsers.length; i++) {
if (iUserId == aUsers[i].iUsersId) {
aUsers.splice(i, 1);
}
}
});
});
});
Any gueses? Please help!
You are deleting the parent with the containers, then trying to access the element.
removing the parent should be in the last step:
$(document).ready(function() {
$("#remove").on("click", function() {
$('input:checked').each(function() {
var iUserId = $(this).closest('span').attr('data-iUserId');
console.log(iUserId);
for (var i = 0; i < aUsers.length; i++) {
if (iUserId == aUsers[i].iUsersId) {
aUsers.splice(i, 1);
}
}
$(this).closest('tr').remove();
});
});
});
Also, consider the comment of #pBuch
The reason is you are looping over the checkboxes and not the span's which have the attribute you are trying to access.
$(this) refers to the checkbox and not the span in the each method you are using:
$('input:checked').each(function() {
// Inside this each statement $(this) refers
// to the the current 'input:checked' element being accessed
});
You should put the data-iUserId attribute on the checkbox since you are accessing that element.
Also! You are missing the closing '>' on the opening span tag:
<span data-iUserId='"+aUsers[i].id+"'</span>
var aUsers = [];
//...somehow populate array...
// We have to assume here that the array got populated
for (var i = 0; i < aUsers.length; i++) {
$("#lblUsers").append('<tr><th scope="row">' + aUsers[i].id + '</th><td>' + aUsers[i].username + '</td><td>' + aUsers[i].firstName + '</td><td>' + aUsers[i].lastName + '</td><td>' + aUsers[i].email + '</td><td>' + "<span data-iUserId='" + aUsers[i].id + "'></span><input type='checkbox' id='chk_" + i + "'" + '</td></tr>');
}
$(document).ready(function() {
$("#remove").on("click", function() {
$("#lblUsers").find('input[type="checkbox"]:checked').each(function() {
// fixed to get the element with the data
var iUserId = $(this).siblings('[data-iUserId]').data('iuserid');
console.log(iUserId);
for (var i = 0; i < aUsers.length; i++) {
// bad practice to use a global aUsers
if (iUserId == aUsers[i].iUsersId) {
aUsers.splice(i, 1);
}
}
$(this).closest('tr').remove();
});
});
});

jquery function calculation no working right on second call

I have a subtotals function that does some calculations on an html table (sums up columns that have assigned classes). I have modified it so that I can pass arguments to it, and on the first function call it works as desired. When I call it again it creates the cell and assigns the class, but the math or apparently something else is wrong because it is returning NaN. Here is my JSFiddle and below is my function. Any help would be appreciated!
//v is parent,z is child element,w is which child column....ex: 0 or 1, y is first run or not, z is class name you want assigned
function subtotals(v, w, x, y, z) {
$(v).each(function (index, element) {
var subTotalAmt = 0;
var numRows = parseInt($(this).attr("rowspan"));
var firstRow = $(this).parent();
var lastRow = firstRow.nextAll('tr').slice(numRows - 2, numRows - 1);
var currentRow = firstRow;
for (i = 0; i < numRows; i++) {
subTotalAmt += parseInt($(currentRow.children(w)[x]).text());
currentRow = currentRow.next("tr");
}
if(y == 'yes'){
lastRow.after('<tr><td class="sub0">Sub Total</td><td class="' + z + '">' + subTotalAmt + '</td></tr>');
$(this).attr('rowspan', numRows + 1);
}
else {
lastRow.append('<td class="' + z + '">' + subTotalAmt + '</td>');
}
});
}
$(function doSubtotals() {
subtotals('.parent','.child','1','yes','sub1');
subtotals('.parent','.child','2','no','sub2');
});
Some of your <td> are not containing a valid number , which case the calculation to fail and put NaN (stands for 'Not a Number') instead of a valid number (NaN + number = NaN).
To fix this i added this condition to your code :
for (i = 0; i < numRows; i++) {
var tdValue=0;
if(!isNaN(parseInt($(currentRow.children(w)[x]).text())))
{
tdValue=parseInt($(currentRow.children(w)[x]).text());
}
subTotalAmt += tdValue;
currentRow = currentRow.next("tr");
}

jQuery - Total and extra divs not showing?

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!

Categories