Updating HTML table from SQL server repeadetly - javascript

I have an HTML page with a table in it which I want to update it's values every 2 seconds with the values stored in the MySQL database.
setInterval(updateSensorsTable, 2000);
setInterval(updatePower, 2000);
function showValue(value) {
document.getElementById("range").innerHTML = value;
}
function TurnLedOn() {
//TODO: need to set the led state and update the sql server
document.getElementById("ledStatus").src = "/LedOn.png";
}
function TurnLedOff() {
//TODO: need to set the led state and update the sql server
document.getElementById("ledStatus").src = "/LedOff.png";
}
function AjaxCaller() {
var xmlhttp = false;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
function callPage(url, div) {
ajax = AjaxCaller();
ajax.open("GET", url, true);
ajax.onreadystatechange = function() {
if (ajax.readyState == 4) {
if (ajax.status == 200) {
div.innerHTML = ajax.responseText;
}
}
}
ajax.send(null);
}
function updateSensorsTable() {
for (i = 0; i <= 7; i++)
callPage('/getVarFromDB.php?offset=' + i, document.getElementById(i));
}
function updatePower() {
document.getElementById("powerValue").innerHTML = '200';
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0" />
<title>SmartLight</title>
</head>
<body bgcolor="#E6E6FA" onload='updateSensorsTable()'>
<br></br>
<table class="sensorsTable" align="center">
<thead>
<tr>
<th>Sensor</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left">GPS</td>
<td align="center" id="0">0</td>
</tr>
<tr>
<td align="left">Temperature</td>
<td align="center" id="1">0</td>
</tr>
<tr>
<td align="left">Pressure</td>
<td align="center" id="2">0</td>
</tr>
<tr>
<td align="left">Light</td>
<td align="center" id="3">0</td>
</tr>
<tr>
<td align="left">Altitude</td>
<td align="center" id="4">0</td>
</tr>
<tr>
<td align="left">Accelerometer</td>
<td align="center" id="5">0</td>
</tr>
<tr>
<td align="left">Humidity</td>
<td align="center" id="6">0</td>
</tr>
<tr>
<td align="left">Camera</td>
<td align="center" id="7">0</td>
</tr>
</tbody>
</table>
<br></br>
<table class="ledTable" align="center">
<tr>
<td align="center">
<input type="image" src="/TurnOn.png" id="turnOn" width="60" height="60" onclick='TurnLedOn()'>
</td>
<td align="center">
<input type="image" src="/TurnOff.png" id="turnOff" width="60" height="60" onclick='TurnLedOff()'>
</td>
<td align="center">
<img src="/LedOn.png" style="width:60px;height:60px" id="ledStatus">
</td>
</tr>
<tr>
<td align="center" id="ledOnButton">LED On</td>
<td align="center" id="ledOffButton">LED Off</td>
<td align="center">LED Status</td>
</tr>
</table>
<div align="center">
Brightness:
<input type="range" name="brightness" min="0" max="100" value="0" step="1" onchange="showValue(this.value)" />
<span id="range">0</span>
<table align="center" class="power">
<tr>
<td align="center" id="powerValue">0</td>
<td align="left">mW</td>
</tr>
</table>
<div align="center">LED Power Meter</div>
</div>
</body>
</html>
Here is the php code:
<?php
include("connect_to_mysql.php");
$result = mysql_query("SELECT value FROM sens" );
echo mysql_result($result,$offset);
Please help me to do this with the correct way.
This code doesn't work when I use the for loop. Using this code with a direct assigment e.g callPage('/getVarFromDB.php?offset=' + 1, document.getElementById(1)); is working

"I have an HTML page with a table
in it which I want to update it's values every 2 seconds with the
values stored in the MySQL database"
Am I missing something? Where does JavaScript enter into this (other than Das Blinkenlights)?
Is there any compelling reason not to just use an HTML page and auto-refresh it every 2 seconds with <meta http-equiv="refresh" content="2000">?
That's the KISS solution.

Change the global to a local: var ajax = AjaxCaller() and this should work.

Related

Page is not getting loaded with fecthed Data using dropdown selection

I am Selecting a dropdown, whose value is passed to a stored procedure as parameter. I am getting the data from database but the data is not getting loaded into same page.
Page A is loaded with data and a dropdown,now once dropdown is selected it should refresh the Page A with newly fetched data but page is rendering the old data. I Am confused.. can anyone help me out ?
i am able to fetch data of the selected dropdown value just that data is not getting loaded into the same page PageA
PageA.cshtml
#foreach (IcebergeWebApplication.Models.UserManager User_det in Model.UserManager)
{
<tr>
<td align="right">User:</td>
<td colspan="2">
<select name="lstuser" width="15px" id="lstuser" onchange="Checked()">
#*<option id="option1" selected>#User_det.user</option>*#
#foreach (IcebergeWebApplication.Models.UserManager1 user_det1 in Model.UserManager1)
{
if (User_det.user == user_det1.user)
{
<option selected="selected" value="#user_det1.id_login">
#user_det1.user
</option>
}
else
{
<option value="#user_det1.id_login">#user_det1.user</option>
}
}
</select>
</td>
<td rowspan="7">
<table border="1" cellspacing="0" cellpadding="1">
<tr>
<td>
ACNA Site(s)
</td>
</tr>
<tr>
<td valign="top">
<table border="0" cellspacing="0" cellpadding="1">
#foreach (IcebergeWebApplication.Models.acna_site acna_Site in Model.acna_site)
{
<tr>
<td>
//checkbox is getting values from DB
<input type="checkbox" name="chkACNASites" id="chkACNASites"/>
</td>
</tr>
}
</table>
</td>
</tr>
</table>
</td>
</tr>
<script>
function Checked()
{
var selected =document.getElementById('lstuser').value;
alert(selected);
$.getJSON(`?handler=SelectuserId&UserId=${selected}`, (data) => {});
}
</script>
PageA.cshtml.cs
public async Task<IActionResult> OnGet()
{
return page{};
}
public void OnGetSelectuserId(int UserId)
{
HttpContext.Session.SetInt32("SelectedUserID",UserId);
OnGet();
}
If you want to replace the html in table,here is a demo:
handler:
public JsonResult OnGetSelectuserId(int UserId) {
return new JsonResult(new List<bool> { true, false, true });
}
html:
<table border="1" cellspacing="0" cellpadding="1">
<tr>
<td>
ACNA Site(s)
</td>
</tr>
<tr>
<td valign="top">
<table border="0" cellspacing="0" cellpadding="1" id="myTable">
#foreach (IcebergeWebApplication.Models.acna_site acna_Site in Model.acna_site)
{
<tr>
<td>
//checkbox is getting values from DB
<input type="checkbox" name="chkACNASites" id="chkACNASites" />
</td>
</tr>
}
</table>
</td>
</tr>
</table>
js:
function Checked() {
var selected = document.getElementById('lstuser').value;
$.getJSON(`?handler=SelectuserId&UserId=${selected}`, (data) => {
var html = "";
data.forEach(function (item, index) {
if (item == true) {
html += "<tr><td><input type='checkbox' name='chkACNASites' id='chkACNASites' checked /></td></tr>";
} else {
html += "<tr><td><input type='checkbox' name='chkACNASites' id='chkACNASites' /></td></tr>";
}
});
document.getElementById("myTable").innerHTML = html;
});
}

For each loop to retrieve multiple messages in page

For a Chrome plugin, I need to retrieve messages. These messages are supplied to me through an html variable.
There are 2 messages in the example provided below and they both start with: <tr bgcolor="#FFFFFF"> and end with: </tr>
I retrieved the first message data, but now I need to make it so that it retrieves all the data from each of those <tr bgcolor="#FFFFFF"> </tr> messages.
What I get provided:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<link rel="STYLESHEET" type="text/css" href="xxx">
<title>Untitled</title>
</head>
<body class="bodySinScrollHor">
<table width="95%" align="center">
<tr>
<td class="etiquetaIzquierda" colspan=6>
<a class="etiquetaIzquierda"><img border=0 height=15 src="xxx"> Comunicaciones (2)</a>
</td>
</td>
</tr>
<tr>
<td colspan=6>
<hr size=1 width="100%">
</td>
</tr>
<tr id="comunicaciones">
<td colspan=6>
<table width="100%" border=0 bordercolor="#000000" cellspacing=0 cellpadding=0>
<tr bgcolor="#FFFFFF">
<td width="9%" class="valorCampoSinTamFijoPeque">2017-08-31T00:00:00</td>
<td width="9%" class="valorCampoSinTamFijoPeque">13:22</td>
<td width="4%" align=left class="valorcampoSinTamFijoPeque">
<img src="xxx" title=" Out">
</td>
<td width="11%" class="valorCampoSinTamFijoPeque" valign=top>
<font class="valorcampoSinTamFijoPeque"><a title="clientname" class="valorcampoSinTamFijoPeque">ClientName</a></font>
</td>
<td width="14%" class="valorCampoSinTamFijoPeque" width="100%">Subject</td>
<!-- <td width="61%"class="valorCampoSinTamFijoPeque">message text here</td> -->
</tr>
<tr bgcolor="#FFFFFF">
<td width="9%" class="valorCampoSinTamFijoPeque">2017-08-31T00:00:00</td>
<td width="9%" class="valorCampoSinTamFijoPeque">13:21</td>
<td width="4%" align=left class="valorcampoSinTamFijoPeque">
<img src="xxx" title=" Out">
</td>
<td width="11%" class="valorCampoSinTamFijoPeque" valign=top>
<font class="valorcampoSinTamFijoPeque"><a title="clientname" class="valorcampoSinTamFijoPeque">ClientName</a></font>
</td>
<td width="14%" class="valorCampoSinTamFijoPeque" width="100%">Subject</td>
<!-- <td width="61%"class="valorCampoSinTamFijoPeque">Message Text Here</td> -->
</tr>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
Below is the code I run to retrieve the data from the first message. Note that there are 2 messages in this case, but there are people that have 54 messages so it needs to loop that many times. This part of the code:
var count = (html1.match(/<tr bgcolor="#FFFFFF">/g) || []).length;
console.log(count);
Is what provides that number for me.
matches[0].forEach(function(match, index) {
var cleintcode = /<div\s*class="t_seg_codCliente">(.*?)<\/div>/.exec(match)[1];
var cleintname = /<div\s*class="t_seg_nomCliente">(.*?)<\/div>/.exec(match)[1];
var taxId = /<div\s*class="t_seg_nifCliente">(.*?)<\/div>/.exec(match)[1];
var date = /<div\s*class="t_seg_fechaPresCliente">(.*?)<\/div>/.exec(match)[1];
var state = /<div\s*class="t_seg_estadoCliente">(.*?)<\/div>/.exec(match)[1];
var expirydate = /<div\s*class="t_seg_fechaCadCliente">(.*?)<\/div>/.exec(match)[1];
var communications = /<div\s*class="t_seg_comCliente"><a .*;">(.*?)<\/a>/.exec(match)[1];
var comclient = /<div\s*class="t_seg_comCliente"><a href="javaScript:popupComs\('(.*?)'/.exec(match)[1];
var messages = "xxx" + comclient;
var html1 = httpGet(messages);
//console.log(html1);
const cleanupDocString = html1.replace(/(?:<!--|-->)/gm, '');
parser = new DOMParser();
htmlDoc = parser.parseFromString(cleanupDocString, "text/html");
//console.log(htmlDoc);
var communicationsvalue = htmlDoc.getElementsByClassName("valorCampoSinTamFijoPeque")[0].textContent;
if (communicationsvalue.indexOf('No existen comunicaciones asociadas a este cliente.') !== -1) {
console.log("This chat does not contain any communiction!");
} else {
//Get count of regex matches. (amount of messages)
var count = (html1.match(/<tr bgcolor="#FFFFFF">/g) || []).length;
console.log(count);
var comDate = htmlDoc.getElementsByClassName("valorCampoSinTamFijoPeque")[0].textContent;
var comTime = htmlDoc.getElementsByClassName("valorCampoSinTamFijoPeque")[1].textContent;
var comType = htmlDoc.getElementsByTagName('img')[1].src;
var comClient = htmlDoc.getElementsByTagName('a')[1].textContent;
var comSubject = htmlDoc.getElementsByClassName("valorCampoSinTamFijoPeque")[6].textContent;
const element = htmlDoc.getElementsByClassName('valorCampoSinTamFijoPeque')[7];
var pulledMessage = element.innerHTML;
var messageData = [{
clientCode: cleintcode,
clientName: cleintname,
taxID: taxId,
cleintDate: date,
cleintState: state,
cleintExpirydate: expirydate
},
{
mesDate: comDate,
mesTime: comTime,
mesType: comType,
mesClient: comClient,
mesSubject: comSubject,
mesText: pulledMessage
}
];
console.log(messageData);
}
});
The code above gives me this console log:
1. 0:
1. cleintDate:"31/08/17"
2. cleintExpirydate:"29/11/17"
3. cleintState:"Subject"
4. clientCode:"xxxxxx"
5. clientName:"clientName"
6. taxID:""
7. __proto__:Object
2. 1:
1. mesClient:"ClientName"
2. mesDate:"2017-08-31T00:00:00"
3. mesSubject:"Subject "
4. mesText:"Message text Here"
5. mesTime:"13:22"
6. mesType:"link"
7. __proto__:Object
Note that array 0 should not change because these messages are from the same person. I just need to grab the second message as well. So I technically need a second array like array 1 containing the data from the second message.
Wanted result:
1. 0:
1. cleintDate:"31/08/17"
2. cleintExpirydate:"29/11/17"
3. cleintState:"Subject"
4. clientCode:"xxxxxx"
5. clientName:"clientName"
6. taxID:""
7. __proto__:Object
2. 1:
1. mesClient:"ClientName"
2. mesDate:"2017-08-31T00:00:00"
3. mesSubject:"Subject "
4. mesText:"Message text Here"
5. mesTime:"13:22"
6. mesType:"link"
7. __proto__:Object
3. 3:
1. mesClient:"ClientName"
2. mesDate:"2017-08-31T00:00:00"
3. mesSubject:"Subject "
4. mesText:"Message text Here"
5. mesTime:"13:22"
6. mesType:"link"
7. __proto__:Object
I know I have to build a for loop, but I have no idea on how do this, so it looks for the second <tr bgcolor="#FFFFFF"> </tr> after the first.
Content is slightly edited to hide personal information.
You may possibly do as follows;
var data = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <link rel="STYLESHEET" type="text/css" href="xxx"> <title>Untitled</title> </head> <body class="bodySinScrollHor"> <table width="95%" align="center"> <tr> <td class="etiquetaIzquierda" colspan=6> <a class="etiquetaIzquierda"><img border=0 height=15 src="xxx"> Comunicaciones (2)</a> </td> </td> </tr> <tr> <td colspan=6> <hr size=1 width="100%"> </td> </tr> <tr id="comunicaciones"> <td colspan=6> <table width="100%" border=0 bordercolor="#000000" cellspacing=0 cellpadding=0> <tr bgcolor="#FFFFFF"> <td width="9%" class="valorCampoSinTamFijoPeque">2017-08-31T00:00:00</td> <td width="9%" class="valorCampoSinTamFijoPeque">13:22</td> <td width="4%" align=left class="valorcampoSinTamFijoPeque"> <img src="xxx" title=" Out"> </td> <td width="11%" class="valorCampoSinTamFijoPeque" valign=top> <font class="valorcampoSinTamFijoPeque"><a title="clientname" class="valorcampoSinTamFijoPeque">ClientName</a></font> </td> <td width="14%" class="valorCampoSinTamFijoPeque" width="100%">Subject</td> <!-- <td width="61%"class="valorCampoSinTamFijoPeque">message text here</td> --> </tr> <tr bgcolor="#FFFFFF"> <td width="9%" class="valorCampoSinTamFijoPeque">2017-08-31T00:00:00</td> <td width="9%" class="valorCampoSinTamFijoPeque">13:21</td> <td width="4%" align=left class="valorcampoSinTamFijoPeque"> <img src="xxx" title=" Out"> </td> <td width="11%" class="valorCampoSinTamFijoPeque" valign=top> <font class="valorcampoSinTamFijoPeque"><a title="clientname" class="valorcampoSinTamFijoPeque">ClientName</a></font> </td> <td width="14%" class="valorCampoSinTamFijoPeque" width="100%">Subject</td> <!-- <td width="61%"class="valorCampoSinTamFijoPeque">Message Text Here</td> --> </tr> </td> </tr> </table> </td> </tr> </table> </body> </html>';
var adiv = document.createElement("div"),
msgs = [],
trs;
adiv.innerHTML = data;
trs = adiv.querySelectorAll('tr[bgcolor="#FFFFFF"]');
trs.forEach(function(tr){
var d = [];
tr.querySelectorAll("td")
.forEach(function(td){
var img = td.querySelector("img"),
src = img && img.attributes.getNamedItem("src").value;
d.push(src || td.textContent);
});
msgs.push(d);
});
console.log(msgs);
Are you looking for this?
var trs = $('tr[bgcolor="#FFFFFF"]');
var output = [];
for(var i=0;i<trs.length;i++){
var currentOutput = {};
currentOutput.cleintDate=trs.eq(i).find("td").eq(0).text();
//other properties like this
currentOutput.cleintExpirydate=trs.eq(i).find("td").eq(1).text();
//add all your required properties
output.push(currentOutput);
}
console.log(output)
Without jquery
var trs = document.querySelectorAll('tr[bgcolor="#FFFFFF"]');
var output = [];
for(var i=0;i<trs.length;i++){
var currentOutput = {};
currentOutput.cleintDate=trs[i].getElementsByTagName('td')[0].innerText;
//other properties like this
currentOutput.cleintExpirydate=trs[i].getElementsByTagName('td')[0].innerText;
//add all your required properties
output.push(currentOutput);
}
console.log(output)

HTML JavaScript - changing info in cell by ID

I've got this problem:
I have a table in HTML, that I want to edit via Javascript.
The table info is of rooms with either value 0 or 1.
I have two buttons that can change a cell, that can set the value to 1 or 0, but I want a function connected to one button, that changes the value, as 1 gets to 0, and 0 gets to 1.
One solution I find is to give each cell an ID and change it, and the other one is to use row/cell from the table.
<table id="table1">
<table border="1" cellpadding="1" cellspacing="3">
<tr>
<td> Room </td>
<td> Status </td>
</tr>
<tr>
<td> r1 </td>
<td id="room1"> 0 </td>
</tr>
<tr>
<td> r2 </td>
<td> 0 </td>
</tr>
<tr>
<td> r3 </td>
<td> 1 </td>
</tr>
Currently I've tried:
<button type="button" onclick="metode1()">Room 1 => 0/1</button>
<button type="button" onclick="metode2()">Room 1 => 0</button>
<script>
function metode1(){
if(document.getElementById("room1").innerHTML > 0) {
document.getElementById("room1").innerHTML = 0;
}
else {
document.getElementById("room1").innerHTML = 1;
}
}
function metode2(){
document.getElementById("table1").rows[1].cells[1].innerHTML = 0;
}
</script>
But neither of them work..
What can I do?
metode1 would work, but your initial text in the element has spaces on either side of the 0, so > can't implicitly convert it to a number. If you remove the spaces (in the markup, or by doing .innerHTML.trim() on a modern browser), the implicit conversion from string to number will work. You might consider converting explicitly, but you'll still have to trim.
Live Example with the spaces removed in the markup:
function metode1() {
if (document.getElementById("room1").innerHTML > 0) {
document.getElementById("room1").innerHTML = 0;
} else {
document.getElementById("room1").innerHTML = 1;
}
}
<table border="1" cellpadding="1" cellspacing="3">
<tr>
<td>Room</td>
<td>Status</td>
</tr>
<tr>
<td>r1</td>
<td id="room1">0</td>
</tr>
<tr>
<td>r2</td>
<td>0</td>
</tr>
<tr>
<td>r3</td>
<td>1</td>
</tr>
</table>
<button type="button" onclick="metode1()">Room 1 => 0/1</button>
Live Example using trim:
function metode1() {
if (document.getElementById("room1").innerHTML.trim() > 0) {
document.getElementById("room1").innerHTML = 0;
} else {
document.getElementById("room1").innerHTML = 1;
}
}
<table border="1" cellpadding="1" cellspacing="3">
<tr>
<td>Room</td>
<td>Status</td>
</tr>
<tr>
<td>r1</td>
<td id="room1"> 0 </td>
</tr>
<tr>
<td>r2</td>
<td>0</td>
</tr>
<tr>
<td>r3</td>
<td>1</td>
</tr>
</table>
<button type="button" onclick="metode1()">Room 1 => 0/1</button>
Note that trim was added in ECMAScript5 (2009) and so may not be on some older JavaScript engines. It's easily shimmed, though.
Try this-
<button type="button" onclick="metode1()">Room 1 => 0/1</button>
function metode1(){
if(document.getElementById("room1").innerHTML.trim() =="1") {
document.getElementById("room1").innerHTML = 0;
}
else {
document.getElementById("room1").innerHTML = 1;
}
}

how to get value from table td using javascript

i want to get the value of Save using jquery through input on keyup function.. i am matching value with Buy..means if value matched with the value(range) of Buy..then get the value of Save..
for example if i entered 3 in textfield then it gets value from Save 45%..and if i entered 8 then result should be 51%..entered 15 result 56% and so on.
here is image link for better understanding.
http://easycaptures.com/fs/uploaded/807/3129634990.jpg
<table class="attribute_table">
<tbody>
<tr>
<th>Buy</th>
<th>Unit</th>
<th>Price/unit</th>
<th class="save_red">Save</th>
</tr>
<tr>
<td>3-5</td>
<td>Pairs</td>
<td class="td_price"><span class="price">$4.99</span></td>
<td class="save_red">45%</td>
</tr>
<tr>
<td>6-11</td>
<td>Pairs</td>
<td class="td_price"><span class="price">$4.49</span></td>
<td class="save_red">51%</td>
</tr>
<tr>
<td>12-23</td>
<td>Pairs</td>
<td class="td_price"><span class="price">$3.99</span></td>
<td class="save_red">56%</td>
</tr>
<tr>
<td>24+</td>
<td>Pairs</td>
<td class="td_price"><span class="price">$3.90</span></td>
<td class="save_red">57%</td>
</tr>
</tbody>
</table>
here is input field
<label for="">Enter Quantity</label>
<input type="text" name="qty" id="qty"></input>
i have tried some code but still no luck..
Try adding data attributes holding the price limits on each td contains the price limits:
$(document).on('input', '#qty', function() {
var that = $(this);
var val = that.val();
if (!isNaN(val)) {
$('.limitTd').each(function() {
var thatTd = $(this);
//var from = parseInt(thatTd.attr('data-from'));
//var to = parseInt(thatTd.attr('data-to'));
var lim = thatTd.html().toString().split('-');
if (lim.indexOf('-') != -1) {
var from = parseInt(lim[0]);
var to = parseInt(lim[1]);
} else {
var from = parseInt(lim.toString().replace('+'));
var to = 9999999;
}
console.log(lim);
if ((val >= from) && (val <= to)) {
var save = thatTd.closest('tr').find('.save_red').html();
$('#saveDiv').html(save);
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="attribute_table">
<tbody>
<tr>
<th>Buy</th>
<th>Unit</th>
<th>Price/unit</th>
<th class="save_red">Save</th>
</tr>
<tr>
<td class="limitTd" data-from="3" data-to="5">3-5</td>
<td>Pairs</td>
<td class="td_price"><span class="price">$4.99</span></td>
<td class="save_red">45%</td>
</tr>
<tr>
<td class="limitTd" data-from="6" data-to="11">6-11</td>
<td>Pairs</td>
<td class="td_price"><span class="price">$4.49</span></td>
<td class="save_red">51%</td>
</tr>
<tr>
<td class="limitTd" data-from="12" data-to="23">12-23</td>
<td>Pairs</td>
<td class="td_price"><span class="price">$3.99</span></td>
<td class="save_red">56%</td>
</tr>
<tr>
<td class="limitTd" data-from="24" data-to="99999">24+</td>
<td>Pairs</td>
<td class="td_price"><span class="price">$3.90</span></td>
<td class="save_red">57%</td>
</tr>
</tbody>
</table>
<label for="">Enter Quantity</label>
<input type="text" name="qty" id="qty"></input>
<div id="saveDiv" style="border:1px solid #d8d8d8;width: 100px;height:50px;float:left"></div>
ALTERNATIVE (No data attributes)
If you don't want to use data attributes, you must manipulate the html to extract the price limits.
For example:
var lim = $('.limitTd').html().split('-');
var from = lim[0];
var to = lim[1];
var mapUnits = [];
$('tr').each(function(i) {
if (!$(this).find("td:nth-child(1)")[0]) {
return;
}
var units = $(this).find("td:nth-child(1)")[0].innerText;
var saveperc = $(this).find("td:nth-child(4)")[0].innerText;
var splits = units.split('-');
var range1 = parseInt(splits[0]);
var range2 = parseInt(splits[1] ? splits[1] : 10000);
mapUnits.push({
range1: range1,
range2: range2,
saveperc: saveperc
})
});
$("#qty").keyup(function() {
$('#saveperc').html('');
var val = $("#qty").val();
for (var m in mapUnits) {
if (mapUnits[m].range1 <= val && mapUnits[m].range2 >= val) {
$('#saveperc').html(mapUnits[m].saveperc);
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="attribute_table">
<tbody>
<tr>
<th>Buy</th>
<th>Unit</th>
<th>Price/unit</th>
<th class="save_red">Save</th>
</tr>
<tr>
<td>3-5</td>
<td>Pairs</td>
<td class="td_price"><span class="price">$4.99</span>
</td>
<td class="save_red">45%</td>
</tr>
<tr>
<td>6-11</td>
<td>Pairs</td>
<td class="td_price"><span class="price">$4.49</span>
</td>
<td class="save_red">51%</td>
</tr>
<tr>
<td>12-23</td>
<td>Pairs</td>
<td class="td_price"><span class="price">$3.99</span>
</td>
<td class="save_red">56%</td>
</tr>
<tr>
<td>24+</td>
<td>Pairs</td>
<td class="td_price"><span class="price">$3.90</span>
</td>
<td class="save_red">57%</td>
</tr>
</tbody>
</table>
<label for="">Enter Quantity</label>
<input type="number" name="qty" id="qty"></input>
<div id='saveperc'></div>
If you cant change the Html, do like this.
Try with -
$('#qty').on('keyup', function() {
var trs = $('table.attribute_table').find('tr:not(:first)');
var val = trs.find('td:first').text();
values = val.split('-');
if ($(this).val() >= values[0] && $(this).val() <= values[1]) {
var dis = trs.find('td.save_red').text();
alert(dis);
}
})

Jquery Javascript function, simple error, can't find it!

When my page loads it calls the function like below:
<body onLoad='changeTDNodes()'>
And the code it calls is below:
enter code here
<script src='jquery-1.4.2.min.js' type='text/javascript'></script>
<script>
function changeTDNodes() {
var threshValue = 10;
$(".threshold").each(function(elem) {
if($("b",elem).innerText > threshValue) {
elem.addClass("overThreshold");
}
});
});
}
I have the class setup correctly in CSS
.overThreshold {
td{font-size:72px;}
th{font-size:72px;}
}
But no classes are being changed, whats going on?
Thanks for all your help!
Below is whole page:
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html>
<head>
<title>Livermore Readerboard</title>
<script src='jquery-1.4.2.min.js' type='text/javascript'></script>
<script>
$(function() {
var threshValue = 10;
$(".threshold").each(function(elem) {
if($("b",elem).innerText > threshValue) {
elem.addClass("overThreshold");
}
});
});
</script>
<style type='text/css'>
#InnerRight {
width: 50% !important;
position: relative !important;
float: left !important;
}
#InnerLeft {
width: 49% !important;
position: relative !important;
float: right !important;
}
.overThreshold {
td{font-size:72px;}
th{font-size:72px;}
}
</style>
</head>
<body>
<div id='InnerLeft'>
<table border=1 cellpading=1 cellspacing=0>
<tr align=right>
<td align=left><b>Split/Skill</b></td>
<td align=center><B>CIQ</b></td>
<td align=center><b>EWT</b></td>
<td align=center><b>Agents Staffed</b></td>
<td align=center><b>Avail</b></td>
</tr>
<tr align=right>
<td align=left><b>LEAD_IP_REP_video</b></td>
<td align=center class='threshold'><B>0</b></td>
<td align=center><b>:00</b></td>
<td align=center><b>3</b></td>
<td align=center><b>2</b></td>
</tr>
<tr align=right>
<td align=left><b>LEAD_IP_REP_tier</b></td>
<td align=center class='threshold'><B>0</b></td>
<td align=center><b>:00</b></td>
<td align=center><b>3</b></td>
<td align=center><b>2</b></td>
</tr>
<tr align=right>
<td align=left><b>IP_REP_video</b></td>
<td align=center class='threshold'><B>60</b></td>
<td align=center><b>10:12</b></td>
<td align=center><b>58</b></td>
<td align=center><b>0</b></td>
</tr>
<tr align=right>
<td align=left><b>IP_REP_hsi</b></td>
<td align=center class='threshold'><B>34</b></td>
<td align=center><b>18:15</b></td>
<td align=center><b>56</b></td>
<td align=center><b>0</b></td>
</tr>
<tr align=right>
<td align=left><b>IP_REP_hn</b></td>
<td align=center class='threshold'><B>0</b></td>
<td align=center><b>3:48</b></td>
<td align=center><b>3</b></td>
<td align=center><b>0</b></td>
</tr>
<tr align=right>
<td align=left><b>IP_REP_cdv</b></td>
<td align=center class='threshold'><B>6</b></td>
<td align=center><b>14:53</b></td>
<td align=center><b>56</b></td>
<td align=center><b>0</b></td>
</tr>
<tr align=right>
<td align=left><b>CommOps FieldCare</b></td>
<td align=center class='threshold'><B>0</b></td>
<td align=center><b>0</b></td>
<td align=center><b>0</b></td>
<td align=center><b>0</b></td>
</tr>
</table>
</div>
</body>
</html>
You would be far better off, if possible, using ids on your elements, and then using document.getElementById() (or, better yet, using Dojo, MooTools or JQuery to make your code simpler).
So your html looks like:
<td id="cell-repair-video">Repair value is <b>23</b></td>
<td id="cell-ppv">PPV value is <b>5</b></td>
Then your JavaScript looks like:
var RepairVideo_cell = document.getElementById("cell-repair-video");
var RepairVideo_value = RepairVideo_cell.getElementsByTagName("b")[0];
In JQuery (and others), you can easily use a class to determine which elements need thresholding
In this case, your html looks like:
<td class="threshold">Repair value is <b>23</b></td>
<td class="threshold">PPV value is <b>5</b></td>
And your entire JavaScript looks like:
$(function() {
var threshValue = 10;
$('.threshold').each(function(index) {
var thisValue = parseFloat( $('b', this).text() );
if(thisValue > threshValue) {
$(this).addClass('overThreshold');
}
});
});
In your current example, there is an error in your CSS
To style td and th elements with a classname, go
td.overThreshold, th.overThreshold {
background: #F00; /* for example */
}
Presumably you are passing through something to the applyThresholds function where innerHTML on myvalue is not valid. Does it work ok in firefox etc?
My guess would be that the crazy document.getElementsByTagName('B')[36]; code is just returning undefined at some point. You should put some code in applyThresholds to check to see if you are getting invalid arguments through. Something like:
if(myvalue == null || mycell == null) {
return;
}

Categories