I using this code for calculating number of times a vehicle is added. The code is not returning the correct value. I want to calculate how many times the same vehicle is selected in each row of the table.
function calculateNumberOfVehicles(vehicleId) {
var returnValue = 0;
var table = $("#selected_students");
table.find('tr').each(function(i, el) {
var counter = 0;
var rowId = $(this).attr('id');
var actualId = rowId.substr(rowId.indexOf("_") + 1).trim();
var addedVehicleId = $("#lockedVehicleId_" + actualId).text();
if (parseInt(vehicleId) == parseInt(addedVehicleId)) {
counter++
returnValue = counter;
}
});
return returnValue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody id="selected_students">
<tr id="row_5ae958a4bb2c561a10003dcc">
<td>Adam Zaffar</td>
<td>L.K.G</td>
<td>Male</td>
<td id="lockedRoute_5ae958a4bb2c561a10003dcc">Karan Nagar</td>
<td id="lockedStop_5ae958a4bb2c561a10003dcc">Lal chowk</td>
<td id="lockedVehicle_5ae958a4bb2c561a10003dcc">JK 123</td>
<td class="delete_row_dynamic"><button relation="5b962874d2ccda10ac003702" title="Delete" id="5ae958a4bb2c561a10003dcc" class="btn btn-danger table_btn btn-outline btn-sm deleteBtn"><i class="fa fa-trash"></i></button></td>
<td id="lockedRouteId_5ae958a4bb2c561a10003dcc" class="hide">5b83dc30d2ccda0b60005c0f</td>
<td id="lockedStopId_5ae958a4bb2c561a10003dcc" class="hide">b930e948-202b-697c-5615-58939cff2ac2</td>
<td id="lockedVehicleId_5ae958a4bb2c561a10003dcc" class="hide">5b962874d2ccda10ac003702</td>
<td id="lockedVehicleIdSeats_5ae958a4bb2c561a10003dcc" class="hide">3</td>
</tr>
<tr id="row_5b17cc27bb2c5633f400197c">
<td>Adnan Mir</td>
<td>L.K.G</td>
<td>Male</td>
<td id="lockedRoute_5b17cc27bb2c5633f400197c">New Jersey City</td>
<td id="lockedStop_5b17cc27bb2c5633f400197c">City Center</td>
<td id="lockedVehicle_5b17cc27bb2c5633f400197c">JK 123</td>
<td class="delete_row_dynamic"><button relation="5b962874d2ccda10ac003702" title="Delete" id="5b17cc27bb2c5633f400197c" class="btn btn-danger table_btn btn-outline btn-sm deleteBtn"><i class="fa fa-trash"></i></button></td>
<td id="lockedRouteId_5b17cc27bb2c5633f400197c" class="hide">5b7fb426d2ccda11fc005185</td>
<td id="lockedStopId_5b17cc27bb2c5633f400197c" class="hide">aa61d076-30c1-31ff-c245-968178042e46</td>
<td id="lockedVehicleId_5b17cc27bb2c5633f400197c" class="hide">5b962874d2ccda10ac003702</td>
<td id="lockedVehicleIdSeats_5b17cc27bb2c5633f400197c" class="hide">3</td>
</tr>
</tbody>
</table>
Try this
var result = calculateNumberOfVehicles('5b962874d2ccda10ac003702');
console.log(result); // This will output the number in console.
function calculateNumberOfVehicles(vehicleId) {
var returnValue = 0;
var table = $("#selected_students");
var counter = 0;
table.find('tr').each(function(i, el) {
var rowId = $(this).attr('id');
var actualId = rowId.substr(rowId.indexOf("_") + 1).trim();
var addedVehicleId = $("#lockedVehicleId_" + actualId).text();
if (parseInt(vehicleId) == parseInt(addedVehicleId)) {
counter++
returnValue = counter;
}
});
return returnValue;
}
function calculateNumberOfVehicles(vehicleId) {
var returnValue = 0;
var table = $("#selected_students");
table.find('tr').each(function (i, el) {
var rowId = $(this).attr('id');
var actualId = rowId.substr(rowId.indexOf("_") + 1).trim();
var addedVehicleId = $("#lockedVehicleId_" + actualId).text();
if (parseInt(vehicleId) == parseInt(addedVehicleId)) {
returnValue++;
}
});
return returnValue;
}
Related
I am trying to change replace an html class based on value.For example if nsndatalength = 0 replace the class name with badge-success
function Awardstable(data) {
var container = document.getElementById('awardsTable');
data.forEach(function(awardsSnap) { // loop over all inventory
var Items = awardsSnap.val();
var nome = Items.Nomenclature;
var NSN = Items.NSN;
var AwardId = Items.Awardid;
var AwrdDate = Items.Awarddate;
var name = Items.Name;
// var quant = Items.Qty;
var cost = Items.Price;
var key = awardsSnap.key;
var NSNref = CatalogueDB.ref("NSNdata/" + NSN).orderByChild("NSN");
if (NSNref) {
// Attach an asynchronous callback to read the data at our posts reference
NSNref.on("value", function(nsnshot) {
if (nsnshot.val()) {
var nsndatalength = Object.keys(nsnshot.val()).length;
} else {
nsndatalength = 0;
}
console.log(nsndatalength)
console.log(nsnshot.val())
var inventoryCard = `
<tr>
<th scope="row">${NSN}</th>
<td>${nome}</td>
<td>${AwardId}</td>
<td>${AwrdDate}</td>
<td class="color-danger">${cost}</td>
<td>
<span class="badge badge-primary" id="sellerqty">${nsndatalength} Sellers</span>
</td>
<td><button type="button" class="btn btn-warning mb-1" id="buymodalbtn" data-toggle="modal" data-target="#buyModal" onclick="buyModal('${NSN}')">
Buy
</button></td>
</tr>
`;
container.innerHTML += inventoryCard;
if (nsndatalength == 0){
var buybtn = document.getElementById('buymodalbtn')
var qtymarker = document.getElementById('sellerqty')
console.log("class",buybtn,qtymarker)
document.getElementById("buymodalbtn").className = document.getElementById("buymodalbtn").className.replace
( /(?:^|\s)btn-warning(?!\S)/g , 'btn-success' )
document.getElementById("sellerqty").className = document.getElementById("sellerqty").className.replace
( /(?:^|\s)badge-primary(?!\S)/g , 'badge-success' )
}
})
} else {
nsndatalength = 0;
console.log("No Awards Available")
}
});
}
The problem is that the code is not working for all inventoryCard. This is the output of the html. The last item 0 sellers and buy button should also change color. What am I doing wrong from the code above?
We can use classList.toggle to toggle a class on/off, with the second parameter we can force it to be on/off.
Here we give the item a unique id:
<span class="badge badge-primary" id="sellerqty-${AwardId}">
then select it with:
document.getElementById(`sellerqty-${AwardId}`)
In your code it would look something like this by giving the item a unique id:
var inventoryCard = `
<tr>
<th scope="row">${NSN}</th>
<td>${nome}</td>
<td>${AwardId}</td>
<td>${AwrdDate}</td>
<td class="color-danger">${cost}</td>
<td>
<span class="badge badge-primary" id="sellerqty-${AwardId}">${nsndatalength} Sellers</span>
</td>
<td>
<button type="button" class="btn btn-warning mb-1" id="buymodalbtn" data-toggle="modal" data-target="#buyModal" onclick="buyModal('${NSN}')">Buy</button>
</td>
</tr>`;
// Add it before we call getElementById
container.innerHTML += inventoryCard;
document.getElementById(`sellerqty-${AwardId}`).classList.toggle('badge-success', nsndatalength == 0)
I am trying to create a function that will colorize the contents of the table based on the values of the row.
I am able to get the data from each row into an array and save the low and high values to a variable. How can I add a class low or high to the low and high values in each row?
In each tr I only want to compare the 1st,2nd,and 3rd position as the zero position is the index.
function showRows(s) {
var t = s.options[s.selectedIndex].text;
var rows = document.getElementById('mytab').getElementsByTagName('tr'),
i = 0,
r, c;
while (r = rows[i++]) {
if (t == 'All') {
r.style.display = ''
} else {
c = r.getElementsByTagName('td')[0].firstChild.nodeValue;
sxval = r.getElementsByTagName('td')[1].firstChild.nodeValue;
fcval = r.getElementsByTagName('td')[2].firstChild.nodeValue;
sgval = r.getElementsByTagName('td')[3].firstChild.nodeValue;
unval = r.getElementsByTagName('td')[4].firstChild.nodeValue;
array = [sxval, fcval, sgval, unval]
var low = Math.min(...array)
var high = Math.max(...array)
console.log("lowest" + " " + low)
console.log("highest" + " " + high)
console.log(c)
console.log(t)
r.style.display = parseInt(c) == parseInt(t) ? '' : 'none';
}
}
}
<body>
<table align="center" border="1" width="50%" cellspacing="0" cellpadding="4">
<tr>
<th>
<select name="mylist" onchange="showRows(this)">
<option value="m1">All</option>
<option value="m2">4</option>
<option value="m3">4.5</option>
<option value="m4">5</option>
</select>
</th>
</tr>
<br>
<table id="mytab" align="center" border="1" width="50%" cellspacing="0" cellpadding="4">
<tr class="content">
<td class="cj-has-text-centered contentcheck">
4 </td>
<td class="cj-has-text-centered">
50 </td>
<td class="cj-has-text-centered">
100 </td>
<td class="cj-has-text-centered">
200 </td>
<td class="cj-has-text-centered">
300 </td>
</tr>
<tr class="content">
<td class="cj-has-text-centered contentcheck">
4.5 </td>
<td class="cj-has-text-centered">
50 </td>
<td class="cj-has-text-centered">
100 </td>
<td class="cj-has-text-centered">
200 </td>
<td class="cj-has-text-centered">
300 </td>
</tr>
<tr class="content">
<td class="cj-has-text-centered contentcheck">
5 </td>
<td class="cj-has-text-centered">
50 </td>
<td class="cj-has-text-centered">
100 </td>
<td class="cj-has-text-centered">
200 </td>
<td class="cj-has-text-centered">
300 </td>
</tr>
</table>
You can use Jquery to do this. Here is the sample. Hope to help, my friend :))
<style>
.highest{
background-color:blue;
}
.lowest{
background-color:red;
}
</style>
function showRows(s) {
var t = s.options[s.selectedIndex].text;
var rows = document.getElementById('mytab').getElementsByTagName('tr'),
i = 0,
r, c;
while (r = rows[i++]) {
if (t == 'All') {
r.style.display = ''
} else {
c = r.getElementsByTagName('td')[0].firstChild.nodeValue;
sxval = r.getElementsByTagName('td')[1].firstChild.nodeValue;
fcval = r.getElementsByTagName('td')[2].firstChild.nodeValue;
sgval = r.getElementsByTagName('td')[3].firstChild.nodeValue;
unval = r.getElementsByTagName('td')[4].firstChild.nodeValue;
array = [sxval, fcval, sgval, unval]
var low = Math.min(...array)
var high = Math.max(...array)
console.log("lowest" + " " + low)
console.log("highest" + " " + high)
console.log(c)
console.log(t)
r.style.display = parseInt(c) == parseInt(t) ? '' : 'none';
//Skip the first column, use :not(:first-child)
$('tr').each(function(){
var vals = $('td:not(:first-child)',this).map(function () {
return parseInt($(this).text(), 10) ? parseInt($(this).text(), 10) : null;
}).get();
// then find their minimum
var min = Math.min.apply(Math, vals);
var max = Math.max.apply(Math, vals);
// tag any cell matching the min and max value
$('td', this).filter(function () {
return parseInt($(this).text(), 10) === min;
}).addClass('highest');
$('td', this).filter(function () {
return parseInt($(this).text(), 10) === max;
}).addClass('lowest');
});
}
}
};
So, I've been recently tasked to do a few calculations and to build a custom JS statistics library. The only 3 things I have left are to create functions for the range, variance, and standard deviation. What I'm doing here is passing my array (x) into the js functions, but they keep coming up blank. Am I doing something wrong?
function findSum(x)
{
var sum = 0;
for(i = 0; i < x.length; i++)
{
sum = sum + x[i];
}
return sum;
};
function findMean(x)
{
return findSum(x) / x.length;
};
function findMedian(x)
{
x.sort( function(a,b) {return a - b;} );
var half = Math.floor(x.length/2);
if(x.length % 2)
return x[half];
else
return (x[half-1] + x[half]) / 2.0;
}
// Ascending functions for sort
function ascNum(a, b) { return a - b; }
function clip(arg, min, max) {
return Math.max(min, Math.min(arg, max));
};
function findMode(x)
{
var arrLen = x.length;
var _arr = x.slice().sort(ascNum);
var count = 1;
var maxCount = 0;
var numMaxCount = 0;
var mode_arr = [];
var i;
for (i = 0; i < arrLen; i++) {
if (_arr[i] === _arr[i + 1]) {
count++;
} else {
if (count > maxCount) {
mode_arr = [_arr[i]];
maxCount = count;
numMaxCount = 0;
}
// are there multiple max counts
else if (count === maxCount) {
mode_arr.push(_arr[i]);
numMaxCount++;
}
// resetting count for new value in array
count = 1;
}
}
return numMaxCount === 0 ? mode_arr[0] : mode_arr;
};
function findRange(x)
{
x.sort( function (a, b) {return a-b;} );
}
function findVariance(x) {
var mean = findMean(x);
return findMean(array.map(findSum(sum)) {
return Math.pow(sum - mean, 2);
}));
},
function findStandardDeviation(x)
{
return Math.sqrt(findVariance(x));
};
The HTML code:
<html>
<head>
<h1>Statistical Calculations</h1>
<title>Calculating Stats</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src='Stats.js'></script>
<script language="JavaScript">
function addNumber()
{
var input = document.getElementById('input').value;
var list = document.getElementById('list');
var option = document.createElement('OPTION');
list.options.add(option);
option.text = input;
}
function getStatistics()
{
var list = new Array();
var select = document.getElementById('list');
for(i = 0; i < select.options.length; i++)
{
list[i] = parseInt(select.options[i].text);
}
document.getElementById('summation').value =findSum(list);
document.getElementById('mean').value = findMean(list);
document.getElementById('median').value = findMedian(list);
document.getElementById('mode').value = findMode(list);
document.getElementById('variance').value = findVariance(list);
document.getElementById('standardDev').value = findStandardDeviation(list);
document.getElementById('range').value = findRange(list);
document.getElementById('max').value = findMax(list);
document.getElementById('min').value = findMin(list);
}
</script>
</head>
<body>
<table>
<tr>
<td>Input Number:</td><td><input type='text' id='input'></td>
</tr>
<tr>
<td colpsan='2'><input type='button' value='Add Number' onClick='addNumber()'></td>
</tr>
<tr>
<td colspan='2'>
<select id='list' size='5'>
</select>
</td>
</tr>
<tr>
<td colpsan='2'><input type='button' value='Calculate!' onClick='getStatistics()'></td>
</tr>
<tr>
<td>Summation:</td><td><input type='text' id='summation' readonly></td>
</tr>
<tr>
<td>Mean:</td><td><input type='text' id='mean' readonly></td>
</tr>
<tr>
<td>Median:</td><td><input type='text' id='median' readonly> </td>
</tr>
<tr>
<td>Mode:</td><td><input type='text' id='mode' readonly></td>
</tr>
<tr>
<td>Max:</td><td><input type='text' id='max' readonly></td>
</tr>
<tr>
<td>Min:</td><td><input type='text' id='min' readonly></td>
</tr>
<tr>
<td>Range:</td><td><input type='text' id='range' readonly></td>
</tr>
<tr>
<td>Variance:</td><td><input type='text' id='variance' readonly></td>
</tr>
<tr>
<td>Standard Deviation:</td><td><input type='text' id='standardDev' readonly></td>
</tr>
</table>
</body>
</html>
The last 3 seem to do absolutely nothing, and I've been bashing my head in for the last few days trying to figure it out. If anyone could help sort my functions out into working order, it'd be greatly appreciated! I'm sure that the array has been passing into the functions correctly, seeing as the first 4 functions obviously worked.
i am writing a code to select/remove the product from display table, and when the product is selected,then product with its price mus be displayed in some other table where at the end sum total is also needed which get updated as per selected product prices
<table id="table-example" class="table">
<thead>
<tr>
<th>Cause</th>
<th>Monthly Charge</th>
</tr>
</thead>
<tbody>
<tr>
<div id="selectedServices"></div>
<td id="myDiv"></td>
</tr>
</tbody>
</table>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<table id="table-example" class="table">
<thead>
<tr>
<th>Cause</th>
<th>Monthly Charge</th>
</tr>
</thead>
<div>
<tbody>
<p>
<tr>
<td>
<input type="checkbox" onclick="ToggleBGColour(this);" />
<label>table</label>
</td>
<td>80</td>
</tr>
<tr>
<td>
<input type="checkbox" onclick="ToggleBGColour(this);" />
<label>chair</label>
</td>
<td>45</td>
</tr>
<tr>
<td>
<input type="checkbox" onclick="ToggleBGColour(this);" />
<label>set</label>
</td>
<td>10</td>
</tr>
</tbody>
</div>
</table>
script
$(function() {
$(":checkbox").change(function() {
var arr = $(":checkbox:checked").map(function() { return $(this).next().text(); }).get();
$("#myDiv").text(arr.join(','));
});
});
function ToggleBGColour(item) {
var td = $(item).parent();
if (td.is('.rowSelected'))
td.removeClass("rowSelected");
else
td.addClass("rowSelected");
}
Here is the corresponding fiddle.
Based on your comment for my other answer, this should work for you then:
$(":checkbox").change(function () {
// Toggle class of selected row
$(this).parent().toggleClass("rowSelected");
// Get all items name, sum total amount
var sum = 0;
var arr = $(":checkbox:checked").map(function () {
sum += Number($(this).parents('tr').find('td:last').text());
return $(this).parents('tr').clone();
}).get();
// Display selected items and their sum
$("#selectedServices").html(arr).find('input').remove();
$("#total").text(sum);
});
This avoids the need for creating new HTML elements in the JavaScript code, and reduces the number of .maps() and .each() loops to one.
http://jsfiddle.net/samliew/uF2Ba/
Here is the javascript for but u need to remove onClick attrs :
$(function() {
$(":checkbox").change(function() {
ToggleBGColour(this);
var arr = $(":checkbox:checked").map(function() {
return $(this).next().text();
}).get();
var nums = $(":checkbox:checked").map(function() {
return parseInt($(this).parent().next().html());
}).get();
var total = 0;
for (var i = 0; i < nums.length; i++) {
total += nums[i] << 0;
}
$("#myDiv").text(arr.join(',') + 'total : '+total);
});
});
function ToggleBGColour(item) {
var td = $(item).parent();
if (td.is('.rowSelected'))
td.removeClass("rowSelected");
else
td.addClass("rowSelected");
}
I updated your fiddle with my answer : http://jsfiddle.net/A2SKr/9/
Here's what i've changed.
Slightly better formatted.
i removed the onclick attribute. Its bad practice to use this because of performance issues. Use delegates
Ive also changed a lil bit of your HTML. the output is now a table
added a total element to the output as well
javascript code :
$(":checkbox").change(function () {
var total = 0;
var check = $(":checkbox:checked");
var causes = check.map(function () {
return $(this).next().text();
}).get();
var costs = check.map(function () {
return $(this).parent().next().text()
}).get();
var tbody = $("#table-example tbody").empty();
$.each(causes, function (i, cause) {
tbody.append("<tr><td>" + cause + "</td><td id='" + i + "'><td/></tr>");
});
$.each(costs, function (i, cost) {
$('#' + i + '').html(cost);
total += parseInt(cost, 10);
});
tbody.append("<tr><td>Total</td><td>" + total + "<td/></tr>");
});
});
I am a student, new to programming and want to learn Javascript by trying stuff. I am doing an exercise which requires me to highlight table cells on mouse drag. I got it to work but I am having problems figuring out how to highlight cells by dragging any direction (not just from X to Y direction). The code below shows how it works from X to Y direction; I want it to do the same when user drags the mouse from Y to X direction.
For example, consider A, B, C, D, G, H and I as table cells.
A B C
D E F
G H I
Dragging the mouse along the diagonal from A to E selects cells A,B,D & E. I want I, H, F, E to be selected on mouse drag from I to E.
Here is the working code:
$(function () {
var isMouseDown = false,
isHighlighted;
var mouseDownRowX = 0;
var mouseDownRowY = 0;
$("#assayPlateTable2 td.dragShadow")
.click(function () {
$("#assayPlateTable2 td").each(function () {
var currClass = $(this).attr('class');
if(currClass == 'dragShadow') {
$(this).css('backgroundColor', 'none');
}
});
var currClass = $(this).attr('class');
if(currClass == 'dragShadow') {
$(this).css('backgroundColor', '#dff0de');
}
currRow = $(this).parent().parent().children().index($(this).parent());
})
.mousedown(function () {
isMouseDown = true;
mouseDownRowX = $(this).parent().parent().children().index($(this).parent());
mouseDownRowY = $(this).parent().children().index($(this));
return false; // prevent text selection
})
.mouseover(function () {
//alert('mouse over' + isMouseDown);
if (isMouseDown) {
currRow = $(this).parent().parent().children().index($(this).parent());
currCol = $(this).parent().children().index($(this));
//var currRow = 1;
//var currCol = 1;
$("#assayPlateTable2 td").each(function () {
_mouseDownRowX = $(this).parent().parent().children().index($(this).parent());
_mouseDownRowY = $(this).parent().children().index($(this));
if(_mouseDownRowX >=
mouseDownRowX && _mouseDownRowX <= currRow && _mouseDownRowY
>= mouseDownRowY && _mouseDownRowY <= currCol) {
var currClass = $(this).attr('class');
if(currClass == 'dragShadow') {
$(this).css('backgroundColor', '#dff0de');
}
//alert("setting==>" + currRow + "," + currCol);
} else {
var currClass = $(this).attr('class');
if(currClass == 'dragShadow') {
$(this).css('backgroundColor', 'none');
}
}
});
for(var i = mouseDownRowX; i < _mouseDownRowX; i++) {
for(var j = mouseDownRowY; j < _mouseDownRowY; j++) {
}
}
//$(this).parent().toggleClass("highlighted", isHighlighted);
//$(this).parent().css('backgroundColor', '#dff0de');
}
})
.bind("selectstart", function () {
return false;
})
$(document)
.mouseup(function () {
isMouseDown = false;
});
});
</script>
HTML:
<table cellpadding="0" cellspacing="0" id="assayPlateTable2">
<tr>
<td class="dragShadow"> </td>
<td class="dragShadow"> </td>
<td class="dragShadow"> </td>
<td class="dragShadow"> </td>
<td class="dragShadow"> </td>
<td class="dragShadow"> </td>
</tr>
<tr>
<td class="dragShadow"> </td>
<td class="dragShadow"> </td>
<td class="dragShadow"> </td>
<td class="dragShadow"> </td>
<td class="dragShadow"> </td>
<td class="dragShadow"> </td>
</tr>
<tr>...</tr> and so on
</table>
For more user friendly in selecting calendar cells, I recommend this one eHighLight Plugin. A very easy and tiny plugin for document element high lighting