JQUERY Conditional Formatting per row - javascript

<script>
$(document).ready(function(){
// Function to get the Max value in Array
Array.max = function( array ){
return Math.max.apply( Math, array );
};
//select row on which conditional formatting will apply
$(".conditional").each(function(){
// get all TDs except for first column
var counts= $(this).find(':nth-child(n+1)');
// return max value
var max = Array.max(counts);
xr = 255;
xg = 255;
xb = 255;
yr = 243;
yg = 32;
yb = 117;
n = 100;
// Iterates on each TD except the first column
$(this).find(':nth-child(n+1)').each(function(){
//assign color based on difference from min and max
var val = parseInt($(this).text());
var pos = parseInt((Math.round((val/max)*100)).toFixed(0));
red = parseInt((xr + (( pos * (yr - xr)) / (n-1))).toFixed(0));
green = parseInt((xg + (( pos * (yg - xg)) / (n-1))).toFixed(0));
blue = parseInt((xb + (( pos * (yb - xb)) / (n-1))).toFixed(0));
clr = 'rgb('+red+','+green+','+blue+')';
$(this).css("background-color",clr);
});
});
});
</script>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style type="text/css">
.year {
background-color: #eeeeee;
font-size: 30px;
text-align: center;
font-weight: bold;
padding: 30px;
}
table.tableizer-table {
border: 1px solid #CCC; font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
margin:auto
}
.tableizer-table td {
padding: 10px;
margin: 5px;
border: 1px solid #ccc;
text-align: center;
width:120px;
}
.tableizer-table th {
background-color: #eeeeee;
color: #111;
font-weight: bold;
padding: 10px;
font-size: 18px;
}
.separator {
background-color: #ffffff;
}
.firstcolumn {
font-weight: bold;
}
</style>
</head>
<body>
<table id="mytable" class="tableizer-table">
<tr><td class="year">2015</td></tr>
<tr class="conditional"><td class="firstcolumn">Hwy (MPGe)</td><td>109</td><td>108</td><td>110</td><td>92</td><td>101</td><td>93</td><td> </td></tr>
<tr class="conditional"><td class="firstcolumn">City (MPGe)</td><td>128</td><td>122</td><td>99</td><td>120</td><td>126</td><td>122</td><td> </td></tr>
<tr class="conditional"><td class="firstcolumn">Combined (MPGe)</td><td>119</td><td> </td><td>105</td><td>105</td><td>114</td><td>114</td><td> </td></tr>
</table>
I am new to Jquery and javascript and trying to implement conditional formatting on a html table. Where the numbers in one row are compared and the lowest element will have a white background and the highest number will have a green background.
The rows on which the conditional formatting needs to work have a class called "conditional". The first column does not contain a number so needs to be excluded from the conditional formatting.
I have been spending several days to do this and cannot succeed.
I found the following piece of code and modified it slightly for my specific needs but it does not work.

I ran it in a browser called from this HTML document:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script src='~/altitude/jquery-2.1.4.min.js'></script>
<script type="text/javascript" src="~/workspace/test.js";></script>
</head>
<body>
<ul id = "squarePos">
<li class = "conditional">Header</div>
<li class = "conditional">1</div>
<li class = "conditional">4</div>
<li class = "conditional">2</div>
<li class = "conditional">3</div>
</ul>
</body>
</html>
The code won't run because you seem to have more than one set of unmatching parenthesis or brackets.
If you use firefox (which I do for web developement) you can hit Ctrl-Shift-K to get a web console that will show you where you have syntax errors in your javascript so you can get on to the debugging.

Related

Localstorage - rewrite from JS to Jquery

I'm working on a portfolio project - which should use jquery - part of the task is to set and get text via localstorage - which I can do in Javascript but I breaks when attempting to refactor in jquery.
I found an elegantly simple javascript codepen, which has all the features I want. But when I refactor into jquery it loses funtionality - I can't save the text to local storage (I get null) and I can't copy the text to a different Div.
This is the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Local Test</title>
</head>
<body>
<div class="content-output"></div>
<textarea class="content-input" placeholder="Your text here"></textarea>
<button class="save-button">Save</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="./script.js"></script>
</body>
</html>
This is simple CSS from the JS code pen:
* {
font-size: 16px;
font-family: sans-serif;
}
body {
padding: 1rem;
font-family: sans-serif;
}
.content-output {
float: left;
box-sizing: border-box;
background: #f9f9f9;
padding: 0.5rem;
width: calc(50% - 1rem);
height: 10rem;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
color: #202020;
}
.content-input {
float: left;
box-sizing: border-box;
margin-left: 2rem;
padding: 0.5rem;
width: calc(50% - 1rem);
height: 10rem;
border: 1px solid #505050;
resize: none;
}
.save-button {
/* -webkit-appearance: none; */
border: 0;
background: #0088ff;
padding: 0.5rem 1rem;
border-radius: 3px;
color: #fff;
margin-top: 1rem;
float: right;
cursor: pointer;
}
Here is the JS which works:
var input_textarea = document.querySelector(".content-input");
var output_div = document.querySelector(".content-output");
var save_button = document.querySelector(".save-button");
save_button.addEventListener("click", updateOutput);
output = localStorage.getItem("content");
input = localStorage.getItem("content");
console.log(output);
output_div.textContent = output;
function updateOutput() {
console.log("clicked button");
localStorage.setItem("content", input_textarea.value);
output_div.textContent = input_textarea.value;
}
And here is the jquery which doesn't work:
var input_textarea = $(".content-input");
var output_div = $(".content-output");
var save_button = $(".save-button");
save_button.on("click", updateOutput);
output_div.textContent = localStorage.getItem("content");
input_textarea.value = localStorage.getItem(("content"));
function updateOutput(event) {
event.preventDefault();
localStorage.setItem("content", input_textarea.value);
output_div.textContent = input_textarea.value;
}
I'm running out of ideas and searches - probably a typo but I cant find it . I've tried text() which was the advice 6 years ago. JSON.stringify and parse don't help because it's just a string.
I'm hoping someone has done some refactoring and spots the differences - I've even run this in the console but I can only add the text to localstorage manually: localstorage.setItem('content', 'help')
Thanks in advance
The problem is that you are trying to select a array, get the value of that array, and output to another array. I think jquery does that when you select a class, (because there could be more than one of them). Simple solution to this..
var input_textarea = $(".content-input")[0];
console.log(input_textarea)
var output_div = $(".content-output")[0];
var save_button = $(".save-button");
save_button.on("click", updateOutput);
output_div.textContent = localStorage.getItem("content");
input_textarea.value = localStorage.getItem(("content"));
function updateOutput(event) {
console.log('hello')
event.preventDefault();
localStorage.setItem("content", input_textarea.value);
output_div.textContent = input_textarea.value;
}
Found it: val() to set and text() to get.
var input_textarea = $(".content-input");
var output_div = $(".content-output");
var save_button = $(".save-button");
save_button.on("click", updateOutput);
// input_textarea.value = localStorage.getItem(("content"));
function updateOutput(event) {
event.preventDefault();
localStorage.setItem("content", input_textarea.val());
output_div.text(localStorage.getItem("content"));
}
this post helped: How to save the value of textarea to localstorage then display it in the same textarea

children of element with column-width move around when clicked with a <body> of a certain size

I cannot manage to reproduce the problem in fiddle.
The problem occurs when is exactly 1286px wide (in the inspector), but it might also happen at other widths.
Clicking the elements changes the height of the body, from 86 to 85.9833.
https://i.imgur.com/rGJPFyW.png
https://gfycat.com/acidicmarvelousabyssiniancat
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
body {font-family: monospace; background: #222; color:#aaa;}
html{scrollbar-color: grey black;}
#ui_tags{
column-width: 80px;
margin: 1em;
padding: 1em;
background-color: #181818;
/*width: 90%;*/
}
.tag_select {
cursor:pointer;
color:#aaa;
}
.tag_select:hover {
background: #222;
}
.tag_select:active {
background: #f00;
}
p {margin-bottom:1px;margin-top:1px;}
</style>
<body>
<div id="ui">
<div id="ui_tags"><p class="tag_select">4ch:114</p><p class="tag_select">avtr:54</p><p class="tag_select">awe:53</p><p class="tag_select">btfl:211</p><p class="tag_select">cat:319</p><p class="tag_select">charc:19</p><p class="tag_select">cmc:145</p><p class="tag_select">dung:15</p><p class="tag_select">frnc:53</p><p class="tag_select">fun:5</p><p class="tag_select">inspr:192</p><p class="tag_select">lego:16</p><p class="tag_select">lndsc:63</p><p class="tag_select">mchn:5</p><p class="tag_select">meh:42</p><p class="tag_select">mnstr:87</p><p class="tag_select">pgrmh:62</p><p class="tag_select">pltc:239</p><p class="tag_select">ppl:22</p><p class="tag_select">pxlr:72</p><p class="tag_select">shrlt:79</p><p class="tag_select">txl:145</p><p class="tag_select">urbn:6</p><p class="tag_select">vlgr:135</p><p class="tag_select">wrd:23</p>
</div>
</div>
<div id="gallery">
</div>
<script type="text/javascript">
window.onload = function(){
var tag_selects = document.getElementsByClassName("tag_select");
for(var i = 0, size = tag_selects.length; i < size ; i++){
// var elem = tag_selects[i].children[1];
var elem = tag_selects[i];
elem.addEventListener("click", function(event){
char = this.innerHTML;
document.getElementById('gallery').innerHTML = char;
});
}
}
</script>
</body>
</html>
I don't know if I'm using bad practices, or how to avoid this problem. I think column-width is not really stable and should be avoided but I'm not sure.
I modified the <p> to <span> and the problem went away.

Assign responseXML values to table cells created by a for loop

I have been playing with JavaScript and Arduino Ethernet Shield for a while and I am trying to send data from Arduino to the webpage it serves using AJAX. The data I send is an array of 24 variables. In order to display the data I created a table in JavaScript using the for() loop. The problem is that when I try to assign the variables to the table cells (one variable per cell), only the first cell of the table receives data. The thing is that when I create the table using HTML (all cells created with the <td></td> tags), the variables are assigned to the table cells properly. Thank you for your time!
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Arduino WebBased Weather Station</title>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<style>
#charset 'UTF-8';#import url(https://fonts.googleapis.com/css?family=Open+Sans:300,400,700);
body {
background-color: black;
font-family: 'Open Sans', sans-serif;
line-height: 1em;
text-align: center;
Color: #cccccc;
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
margin-left:auto;
margin-right:auto;
}
th {
border: 1px solid #336699;
color:#0040ff;
text-align: center;
padding: 8px;
}
td {
border: 1px solid #336699;
color:#0080ff;
text-align: center;
padding: 8px;
}
td.td2 {
border: 1px solid #336699;
color:#0080ff;
text-align: left;
padding: 8px;
}
</style>
<h1>Arduino Web-Based Weather Station</h1><hr>
<h3>WELCOME!</h3>
<p>Project is hosted on github. Please visit my <a href='https://github.com/zissis-pap'>page</a> for more!</p><hr>
</head>
<body onload="BuiltArray(); GetArduinoIO()"><br>
<div id="array1"></div>
<script>
var bool = false;
function BuiltArray() {
var arr1 ="<table style='width:100%'><tr><th colspan='25'>\
AVERAGE CONDITIONS FOR THE LAST 24 HOURS</th></tr><tr><td\ class='td2'>HOURS:</td>"
for (var i = 0; i <= 23; i++) {
arr1 += "<td><font color='#3d0099'>\
<span class='hrs'>...</span></font></td>";
}
arr1 += "</tr></table>";
document.getElementById("array1").innerHTML = arr1;
bool = true;
}
function GetArduinoIO() {
if(bool == true) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
if (this.responseXML != null) {
// XML file received - contains analog values, switch values and LED states
var count;
// get analog inputs
var num_an = this.responseXML.getElementsByTagName('hours').length;
for (count = 0; count < num_an; count++) {
document.getElementsByClassName("hrs")[count].innerHTML =
this.responseXML.getElementsByTagName('hours')[count].childNodes[0].nodeValue;
}
}
}
}
}
// send HTTP GET request with LEDs to switch on/off if any
request.open("GET", "ajax_inputs", true);
request.send();
setTimeout('GetArduinoIO()', 2000);
}
}
</script>
</body>
</html>

time shown is blank for javascript application

can someone take a look at this and tell me what I'm doing wrong?
I wanted to use these other techniques just as an exercise.
such as using element id / using a separate js file to recreate a clock application that shows the current date. However, it keeps showing up as blank:
"use strict";
var $ = function(id) { return document.getElementById(id); };
var padSingleDigit = function(num) {
return (num < 10) ? "0" + num : num;
};
// callback function for displaying clock time
var displayTime = function(now) {
$("hours").firstChild.nodeValue = now.hours;
$("minutes").firstChild.nodeValue = padSingleDigit(now.minutes);
$("seconds").firstChild.nodeValue = padSingleDigit(now.seconds);
$("ampm").firstChild.nodeValue = now.ampm;
// display date in "m/d/yyyy" format - correct for zero-based month
var date = (now.getMonth() + 1) + "/" + now.getDate() + "/" + now.getFullYear();
$("date").firstChild.nodeValue = date;
};
// onload event handler
window.onload = function() {
var clock = createClock(displayTime);
// start clock
clock.start();
};
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 450px;
border: 3px solid blue;
padding: 0 2em 1em;
}
h1 {
color: blue;
}
label {
float: left;
width: 11em;
text-align: right;
padding-bottom: .5em;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
fieldset {
margin-bottom: 1em;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Clock</title>
<link rel="stylesheet" href="clock.css">
<script src="clock.js"></script>
</head>
<body>
<main>
<h1>Digital clock</h1>
<fieldset>
<legend>Clock</legend>
<span id="date"> </span>:
<span id="minutes"> </span>:
<span id="seconds"> </span>
<span id="ampm"> </span>
</fieldset>
</main>
</body>
</html>
The problem is you are referencing an element that does not exist. There is no element with the id of "hours" in your code.

10+1000 won't return the right number Javascript

I have a simple script asking a user for numbers.Each number is added into a variable called counter.I want this to happen as long as counter < 100
After that i want to show the user how many numbers he entered and the result.
The problem is that if the user presses 10 and the second time 1000 he will get back number 01001000
Any ideas?
<!DOCTYPE html>
<html>
<head>
<title>Δομημένος προγραμματισμός</title>
<meta charset="utf-8"/>
<!--<link rel="stylesheet" type="text/css" href="http://kounj.web44.net/css/apps/borderRadius.css">-->
<style type="text/css">
button, .button {
border: 0px;
padding: 15px;
font-size: 18px;
color: green;
font-style: italic;
font-family: sans-serif;
border-radius: 6px;
border-left:4px dashed #f22aa9;
background-color: #ddd;
margin: 0;
display: inline-block;
}
.button{
display: block;
width: 20%;
}
</style>
<script type="text/javascript">
function wh(){
var i=0;
var counter=0;
while(counter < 100){
i++;
var number=prompt("Give me num");
counter=counter +number;
}
alert(i);
alert(counter);
}
</script>
</head>
<body>
<div class="button" onclick="wh();">counter</div>
</body>
</html>
You are concatenating strings. Any data input in a prompt is treated as a string. You need to convert to integer using parseInt() before adding to get proper integer math.
function wh(){
var i = 0;
var counter = 0;
while(counter < 100){
i++;
var input = prompt("Give me num");
var number = parseInt(input, 10);
counter = counter + number;
}
alert(i);
alert(counter);
}

Categories