How can I get the highest value in a table column by class? I have tried the following:
HTML
<table>
<tr><td class="speed">1.1</td></tr>
<tr><td class="speed">3.1</td></tr>
<tr><td class="speed">5.5</td></tr>
<tr><td class="speed">2.0</td></tr>
</table>
jQuery/Javascript
function gethighestspeeds(){
var speeds = $(".speed").map(function() {
return parseFloat(this.text, 10);
}).get();
var highestspeed = Math.max.apply(Math, speeds);
alert(highestspeed)
}
Also, how can I get all values if > than a certain number?
this.text is undefined for the td element, you need to parse parseFloat($(this).text(), 10);
function gethighestspeeds() {
var speeds = $(".speed").map(function() {
return parseFloat($(this).text(), 10);
}).get();
var highestspeed = Math.max.apply(Math, speeds);
snippet.log('high: ' + highestspeed);
var num = 2.3;
var array = $(".speed").map(function() {
var flt = parseFloat($(this).text(), 10);
return flt > num ? flt : undefined;
}).get();
snippet.log('array: ' + array)
//if you already have the speeds array
var array2 = speeds.filter(function(val) {
return num < val;
});
snippet.log('array2: ' + array)
}
gethighestspeeds();
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="speed">1.1</td>
</tr>
<tr>
<td class="speed">3.1</td>
</tr>
<tr>
<td class="speed">5.5</td>
</tr>
<tr>
<td class="speed">2.0</td>
</tr>
</table>
Try this........
var certainNumber=2.2; //Whatever you want to set
function gethighestspeeds(){
var speeds = $(".speed").map(function() {
return parseFloat(this.text, 10) > parseFloat(certainNumber);
}).get();
}
You have to use : $(this).text() instead of this.text in your map function:
return parseFloat($(this).text(), 10);
Related
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.
GOAL On sort return entire contents of div class="box"
I have x 4, each DIV has a variable "object".
The variable "object" works fine, the script finds the object adds 10 and then sorts correctly. In this example the script returns 20, 13, 11, 10 sorted greater to lower correctly. I need to return the contents of the entire div class="box", not just the object item.
...
20 b b b b,
13 c c c c,
11 a a a a,
10 d d d d,
<!--CSS ===-->
<style type="text/css">
.box {
border: 1px solid #000;
padding: 2px;
margin: 2px;
}
</style>
<!--HTML ===-->
<div id="containerSort">
<div class="box">
<object>
001
</object>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>a</td>
<td>a</td>
<td>a</td>
<td>a</td>
</tr>
</table>
</div>
<div class="box">
<object>
10
</object>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>b</td>
<td>b</td>
<td>b</td>
<td>b</td>
</tr>
</table>
</div>
<div class="box">
<object>
03
</object>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>c</td>
<td>c</td>
<td>c</td>
<td>c</td>
</tr>
</table>
</div>
<div class="box">
<object>
0
</object>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>d</td>
<td>d</td>
<td>d</td>
<td>d</td>
</tr>
</table>
</div>
<div id="increase"></div>
</div>
<!--JS ===-->
<script type='text/javascript'>//<![CDATA[
$(document).ready(function() {
$("#increase").trigger("click");
});
// Assign function as eventListener
$("#increase").click(computeAndUpdateValue);
// Wrapper function
function computeAndUpdateValue() {
var valArr = getValues();
valArr = addNumber(valArr);
valArr = sortValues(valArr);
createAndRenderHTML(valArr, "#containerSort");
}
function getValues(){
var returnArray = [];
$("div.box").each(function(id, el) {
returnArray.push(parseInt($(el).text(), 10));
});
return returnArray;
}
function addNumber(arr) {
return arr.map(function(item) {
return parseInt(item, 10) + 10;
});
}
function sortValues(arr) {
return arr.sort(function(a, b) {
return a > b ? -1 : a < b ? 1 : 0
});
}
function createAndRenderHTML(arr, el) {
var _html = arr.map(function(item) {
return "<div class='box'> <object>" + item + "</object></div>"
}).join("");
$(el).html(_html);
}
//]]>
</script>
This can be actually simplify, but as of now below solution will solve your problem
$(document).ready(function() {
$("#increase").trigger("click");
});
// Assign function as eventListener
$("#increase").click(computeAndUpdateValue);
// Wrapper function
function computeAndUpdateValue() {
var valArr = getValues();
valArr = addNumber(valArr);
valArr = sortValues(valArr);
createAndRenderHTML(valArr, "#containerSort");
}
function getValues() {
var returnArray = [];
$("div.box").each(function(id, el) {
returnArray.push($(el));
});
return returnArray;
}
function addNumber(arr) {
return arr.map(function(item) {
var $object = $(item).find("object");
$object.text(parseInt($object.text(), 10) + 10);
return item;
});
}
function sortValues(arr) {
return arr.sort(function(a, b) {
a = parseInt($(a).find("object").text(), 10);
b = parseInt($(b).find("object").text(), 10);
return a > b ? -1 : a < b ? 1 : 0;
});
}
function createAndRenderHTML(arr, el) {
var _html = arr.map(function(item) {
return "<div class='box'> <object>" + item.text() + "</object></div>"
});
$(el).empty().append(_html);
}
What I am doing here is
creating the array of object
sorting that object on the basis of value in object tag
appending sorted array in container
I have created a js fiddle at : https://jsfiddle.net/7pjL17bu/
If you don't want to put whole div content then see the edited fiddle at : https://jsfiddle.net/7pjL17bu/1/
it is better to extend valArr array to object since you want to store more that one data field,
so now in valArr there is int key which stands for value in <object> tag and content key is a string with <td> tags contents.
I've also changed all there functions so they'll be working with object data type :
$(document).ready(function() {
$("#increase").trigger("click");
});
// Assign function as eventListener
$("#increase").click(computeAndUpdateValue);
// Wrapper function
function computeAndUpdateValue() {
var valArr = getValues();
valArr = addNumber(valArr);
console.log(valArr);
valArr = sortValues(valArr);
createAndRenderHTML(valArr, "#containerSort");
}
function getValues() {
var returnArray = [];
$("div.box").each(function(id, el) {
var content = "";
$(el).find("td").each(function(id, el) {
content += " "+$(el).text();
});
returnArray.push({int:parseInt($(el).text(), 10),content: content});
});
return returnArray;
}
function addNumber(arr) {
return arr.map(function(item) {
console.log(item);
return {int:parseInt(item.int, 10) + 10, content: itemcontent};
});
}
function sortValues(arr) {
return arr.sort(function(a, b) {
return a > b ? -1 : a < b ? 1 : 0;
});
}
function createAndRenderHTML(arr, el) {
var _html = arr.map(function(item) {
return "<div class='box'> <object>" + item.int +" "+item.content+"</object></div>";
}).join("");
$(el).html(_html);
}
You can check out my implementation here: https://jsfiddle.net/eko24ive/npt3wa95/
I'm trying to check if a certain number is contained within an array.
I have tried using if (value in mines) and var value = this.value; var isMine = mines.indexOf(value);
But neither of these are working as expected. Can anyone explain why?
FIDDLE
JS
var mines = []
while (mines.length < 9){
var randomnumber=Math.ceil(Math.random() * 30)
var found=false;
for(var i=0;i<mines.length;i++){
if(mines[i]==randomnumber){found=true;break}
}
if(!found)mines[mines.length]=randomnumber;
}
$(document).ready(function() {
$(".blank").click(function() {
var value = this.value;
if (value in mines) {
$(this).removeClass("blank");
$(this).addClass("bomb");
} else {
$(this).removeClass("blank");
$(this).addClass("safe");
}
});
});
HTML
<div class="background">
<table>
<tr>
<td colspan="10"><div class="title">title here</div></td>
</tr>
<tr>
<td colspan="10"><div class="info">text here</div></td>
</tr>
<tr>
<td><button class="blank" value="1"></button></td>
<td><button class="blank" value="2"></button></td>
<td><button class="blank" value="3"></button></td>
</tr>
<table>
</div>
When it's an array you should be using indexOf, but you have two major issues.
Firstly the type has to match. The array has numbers, but the value of an element is always a string.
The easy solution is to parse the value as an integer
var value = parseInt( this.value, 10 );
Secondly, indexOf returns the index, and it will return 0 for the first item in the array, and 0 is falsy, so you have to actually check for -1, which is what indexOf returns if there is no match
if (mines.indexOf(value) != -1) { ...
FIDDDLE
A little simplified you'd end up with
var mines = [];
while (mines.length < 9){
var randomnumber = Math.ceil(Math.random() * 30);
if ( mines.indexOf(randomnumber) == -1 )
mines.push(randomnumber);
}
$(document).ready(function() {
$(".blank").click(function() {
var isBomb = mines.indexOf( parseInt( this.value, 10 )) != -1;
$(this).removeClass('blank').addClass(isBomb ? 'bomb' : 'safe');
});
});
FIDDLE
var value = +this.value
convert string to integer
You can just do this:
var myArray = ["one", "two", "three", "four"];
var myString = myArray.join("***") + "***";
var mySubstring = "four";
var inArray = myString.indexOf(mySubstring + "***");
if(inArray >= 0){alert("It's in array");}
this.value returns a string. Try this. Updated fiddle
if (mines.indexOf(parseInt(value))!=-1) { //or if (parseInt(value) in mines) {
$(this).removeClass("blank");
$(this).addClass("bomb");
} else {
$(this).removeClass("blank");
$(this).addClass("safe");
}
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>");
});
});