How to ensure that multiple setinterval functions are not intefering - javascript

I have created two calculators on a page, the second one calculates properly, however the first one does not. I believe that this is due to my two setinterval functions interfering. How do I get both of these functions to work in conjunction.
var x = document.getElementById("x");
var d = document.getElementById("d");
var xstored = x.getAttribute("data-in");
setInterval(function() {
if (x == document.activeElement) {
var temp = x.value;
if (xstored != temp) {
xstored = temp;
x.setAttribute("data-in", temp);
calculate();
}
}
}, 10);
function calculate() {
d.innerHTML = x.value * .62;
}
var a = document.getElementById("a");
var b = document.getElementById("b");
var astored = a.getAttribute("data-in");
var c = document.getElementById("c")
setInterval(function() {
if (a == document.activeElement) {
var temp = a.value;
if (astored != temp) {
astored = temp;
a.setAttribute("data-in", temp);
calculate();
}
}
}, 50);
function calculate() {
b.innerHTML = a.value * .62;
c.innerHTML = Math.round(a.value * .0103);
}
function tisNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
<table style="width:100%;text-align: center;">
<tbody>
<tr>
<td style="width:50%;background:none;">
<p style="margin: 0px;font-weight: bold;font-size: 35px;">Lawn Square Footage</p>
</td>
<td style="width:50%;font-size: 35px;font-weight: bold;background:none">
<p style="margin: 0px;font-weight: bold;font-size: 35px;">Water Usage</p>
</td>
</tr>
<tr>
<td style="width:50%;">
<input id="x" onkeypress="return isNumberKey(event)" data-in="" type="text" style="height: 250px;margin-top: 10px;width: 250px;text-align: center;font-size: 100px" />
</td>
<td style="width:50%;font-size: 100px;"><span id="d" class="counter"></span>
</td>
</tr>
</tbody>
</table>
<table style="width:100%;text-align: center;">
<tbody>
<tr>
<td style="width:33%;background:none;">
<p style="margin: 0px;font-weight: bold;font-size: 35px;">Lawn Square Footage</p>
</td>
<td style="width:33%;font-size: 35px;font-weight: bold;background:none">
<p style="margin: 0px;font-weight: bold;font-size: 35px;">Water Usage</p>
</td>
</tr>
<tr>
<td style="width:33%;">
<input id="a" onkeypress="return tisNumberKey(event)" data-in="" type="text" style="height: 250px;margin-top: 10px;width: 250px;text-align: center;font-size: 100px" />
</td>
<td style="width:33%;font-size: 100px;"><span id="b" class="counter"></span>
</td>
<td style="width:33%;">
<p style="font-size:50px; font-weight:bold;">Your lawn takes a <span id="c"></span> hour shower
</td>
</tr>
</tbody>
</table>
http://codepen.io/anon/pen/qdyPjE

You can't have 2 functions with the same name/signature. You have calculate() twice you should name one different like calculate1(). You are overriding the first calculate() function with the second one that is why the second one works but the first one doesn't...

Multiple setInterval functions will never interfere with one another, your script runs on a single thread. The functions are queued and will execute one after the other. You don't need to worry about two different functions trying same data at the same time.
Your actual problem appears to be that you have two functions with same name, as pointed out already in another answer.

Related

how to get data from one textbox to another textbox in dynamically generated html table?

below is my code. in that code when i enter 3 in txtbox and click copy.then same table will be generated 3 times. if i enter name and id in txtbox 1 and 2 and click get data then it will be set to txtbox 3 and 4.it works fine only with first table. the problem is it is not working with dynamic tables.help me!!
the code as follows,
function copytbl() {
var i, j;
j = document.getElementById("txtbox").value;
for (i = 0; i < j - 1; i++) {
var row = document.getElementById("tblbdy"); // find row to copy
var table = document.getElementById("tbl"); // find table to append to
var clone = row.cloneNode(true); // copy children too
clone.id = "newID"; // change id or other attributes/contents
table.appendChild(clone); // add new row to end of table
}
}
function getdata() {
document.getElementById("txtbox3").value = document.getElementById("txtbox1").value;
document.getElementById("txtbox4").value = document.getElementById("txtbox2").value;
}
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
table,
td {
border: 1px solid black;
border-collapse: collapse;
height: 90px;
text-align: left;
}
tr.noBorder td {
border-right-style: hidden;
border-left-style: hidden;
}
<input type="text" id="txtbox" name="textbox" onkeypress="return isNumber(event)" />
<input type="reset" value="Reset">
<button type="button" onclick="copytbl()">COPY</button><br>
<br>
<table id="tbl" style="width:100%">
<tbody id="tblbdy">
<tr>
<td colspan="5">Header</td>
</tr>
<tr>
<td>Name</td>
<td colspan="3">Age</td>
<td>Sex</td>
</tr>
<tr>
<td rowspan="3">
Name:<br>
<input type="text" id="txtbox1" name="textbox" /><br> Id:
<br>
<input type="text" id="txtbox2" name="textbox" onkeypress="return isNumber(event)" /><br>
<input type="reset" value="Reset">
</td>
<td></td>
<td></td>
<td></td>
<td rowspan="3">
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<br>
</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td colspan="4"></td>
</tr>
<tr>
<td colspan="5">Footer</td>
</tr>
<tr class="noBorder">
<td>
<br>
<button type="button" onclick="getdata()">GET DATA</button><br><br> Name:
<br>
<input type="text" id="txtbox3" name="textbox" /><br> Id:
<br>
<input type="text" id="txtbox4" name="textbox" /><br>
</td>
</tr>
</table>
thanks in advance
You need to change the id's you are using into classes. Then parse the new tbody id you generate into the getdata Function
Demo https://jsfiddle.net/kplcode/bt5da5go/2/
function copytbl() {
var i, j;
j = document.getElementById("txtbox").value;
for (i = 0; i < j - 1; i++) {
var newId = "newID-"+(document.querySelectorAll('.tblbdy-ele').length+i);
var row = document.getElementById("tblbdy"); // find row to copy
var table = document.getElementById("tbl"); // find table to append to
var clone = row.cloneNode(true); // copy children too
clone.id = newId; // change id or other attributes/contents
table.appendChild(clone); // add new row to end of table
var getDataBtn = document.getElementById(newId).getElementsByClassName("getDataBtn")[0]
getDataBtn.onclick = function() {
getdata(newId);
};
}
}
function getdata(id) {
var table = document.getElementById(id);
document.getElementById(id).getElementsByClassName("txtbox3")[0].value = document.getElementById(id).getElementsByClassName("txtbox1")[0].value;
document.getElementById(id).getElementsByClassName("txtbox4")[0].value = document.getElementById(id).getElementsByClassName("txtbox2")[0].value;
}
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}

How to determine how many years (D/M/Y) left from the Birthday to a certain age in age calculator?

What should I need to change to determine how many years (D/M/Y) left from the Birthday to a certain age? i.e my birthday is 01.01.1990 and and today my age is 27 Years, 5 month.... and I will 50 years old in 2040.
I want to know How many years left (DD/M/Y) from today to become 50 years old?
Another thing is Concern title should be just above the result not left side of the result.
Code below for this script and and two picture regarding this..
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
function wr_document()
{
var w=new Date();
var s_d=w.getDate();
var s_m=w.getMonth()+1;
var s_y=w.getFullYear();
document.cir.len11.value=s_d;
document.cir.len12.value=s_m;
document.cir.len13.value=s_y;
}
function isNum(arg)
{
var args = arg;
if (args == "" || args == null || args.length == 0)
{
return false;
}
args = args.toString();
for (var i = 0; i<args.length; i++)
{
if ((args.substring(i,i+1) < "0" || args.substring(i, i+1) > "9") && args.substring(i, i+1) != ".")
{
return false;
}
}
return true;
}
function checkday(aa)
{
var val = aa.value;
var valc = val.substring(0,1);
if(val.length>0 && val.length<3)
{
if(!isNum(val) || val == 0)
{
aa.value="";
}
else if( val < 1 || val > 31)
{
aa.value=valc;
}
}
else if(val.length>2)
{
val = val.substring(0, 2);
aa.value=val;
}
}
function checkmon(aa)
{
var val = aa.value;
var valc = val.substring(0,1);
if(val.length>0 && val.length<3)
{
if(!isNum(val) || val == 0)
{
aa.value="";
}
else if(val < 1 || val > 12)
{
aa.value=valc;
}
}
else if(val.length>2)
{
val = val.substring(0, 2);
aa.value=val;
}
}
function checkyear(aa)
{
var val = aa.value;
var valc = val.substring(0,(val.length-1));
if(val.length>0 && val.length<7)
{
if(!isNum(val) || val == 0)
{
aa.value=valc;
}
else if(val < 1 || val>275759)
{
aa.value="";
}
}
else if(val.length>4)
{
aa.value=valc;
}
}
function checkleapyear(datea)
{
if(datea.getYear()%4 == 0)
{
if(datea.getYear()% 10 != 0)
{
return true;
}
else
{
if(datea.getYear()% 400 == 0)
return true;
else
return false;
}
}
return false;
}
function DaysInMonth(Y, M) {
with (new Date(Y, M, 1, 12)) {
setDate(0);
return getDate();
}
}
function datediff(date1, date2) {
var y1 = date1.getFullYear(), m1 = date1.getMonth(), d1 = date1.getDate(),
y2 = date2.getFullYear(), m2 = date2.getMonth(), d2 = date2.getDate();
if (d1 < d2) {
m1--;
d1 += DaysInMonth(y2, m2);
}
if (m1 < m2) {
y1--;
m1 += 12;
}
return [y1 - y2, m1 - m2, d1 - d2];
}
function calage()
{
var curday = document.cir.len11.value;
var curmon = document.cir.len12.value;
var curyear = document.cir.len13.value;
var calday = document.cir.len21.value;
var calmon = document.cir.len22.value;
var calyear = document.cir.len23.value;
if(curday == "" || curmon=="" || curyear=="" || calday=="" || calmon=="" || calyear=="")
{
alert("Please fill all the values and click 'Go'");
}
else if(curday == calday && curmon==calmon && curyear==calyear)
{
alert("Today your birthday & Your age is 0 years old")
}
else
{
var curd = new Date(curyear,curmon-1,curday);
var cald = new Date(calyear,calmon-1,calday);
var diff = Date.UTC(curyear,curmon,curday,0,0,0)
- Date.UTC(calyear,calmon,calday,0,0,0);
var dife = datediff(curd,cald);
document.cir.val.value=dife[0]+" years, "+dife[1]+" months, and "+dife[2]+" days";
var secleft = diff/1000/60;
document.cir.val3.value=secleft+" minutes since your birth";
var hrsleft = secleft/60;
document.cir.val2.value=hrsleft+" hours since your birth";
var daysleft = hrsleft/24;
document.cir.val1.value=daysleft+" days since your birth";
//alert(""+parseInt(calyear)+"--"+dife[0]+"--"+1);
var as = parseInt(calyear)+dife[0]+1;
var diff = Date.UTC(as,calmon,calday,0,0,0)
- Date.UTC(curyear,curmon,curday,0,0,0);
var datee = diff/1000/60/60/24;
document.cir.val4.value=datee+" days left for your next birthday";
}
}
function color(test)
{
for(var j=7; j<12; j++)
{
var myI=document.getElementsByTagName("input").item(j);
//myI.setAttribute("style",ch);
myI.style.backgroundColor=test;
}
}
function color1(test)
{
var myI=document.getElementsByTagName("table").item(0);
//myI.setAttribute("style",ch);
myI.style.backgroundColor=test;
}
</script>
<style media="screen" type="text/css">
.cal-container {
width: 540px;
margin: 10px auto 0;
}
#age-calculator {
background: none repeat scroll 0 0 #DDDDDD;
border: 1px solid #BEBEBE;
padding-left: 20px;
}
.calc {
border-color: #AAAAAA #999999 #929292 #AAAAAA;
border-style: solid;
border-width: 1px 2px 2px 1px;
padding: 2px 30px 3px;
height: 27px;
}
.calc:active {
border-color: #AAAAAA #999999 #929292 #AAAAAA;
border-style: solid;
border-width: 1px;
}
</style>
<title>Age calculator</title>
</head>
<body onLoad="wr_document()">
<div class="cal-container">
<div id="calculator-container">
<table width="100%" cellspacing="0" cellpadding="0" border="0">
<tbody>
<tr>
<td valign="top">
<h1 style="padding-top: 10px;">Age Calculator</h1>
<div class="descalign">
<span>Calculate your age in days, years, minutes, seconds. Know how many days are left for your next birthday.</span><br/><br/>
</div>
<div id="age-calculator">
<table width="100%" cellspacing="4" cellpadding="0" border="0" bgcolor="">
<tbody>
<tr>
<td colspan="2">
<table class="result" width="100%" height="100%">
<tbody>
<tr>
<td>
<form name="cir">
<table cellspacing="0" cellpadding="3">
<tbody>
<tr>
<td colspan="2">
<br>
Today's Date is:
</td>
</tr>
<tr>
<td align="center" colspan="2">
Date -
<input class="innerc resform" type="text" value="" onkeyup="checkday(this)" size="2" name="len11">
Month -
<input class="innerc resform" type="text" value="" onkeyup="checkmon(this)" size="2" name="len12">
Year -
<input class="innerc resform" type="text" value="" onkeyup="checkyear(this)" size="4" name="len13">
<br>
<br>
</td>
</tr>
<tr>
<td colspan="2"> Enter Your Date of Birth : </td>
</tr>
<tr>
<td align="center" colspan="2">
Date -
<input class="innerc resform" type="text" onkeyup="checkday(this)" size="2" name="len21">
Month -
<input class="innerc resform" type="text" onkeyup="checkmon(this)" size="2" name="len22">
Year -
<input class="innerc resform" type="text" onkeyup="checkyear(this)" size="4" name="len23">
<br>
<br>
<input class="calc" type="button" onclick="calage()" value=" Go " name="but">
<br>
<br>
</td>
</tr>
<tr>
<td class="form" width="30%" align="center">
<b> </b>
</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td>
<b> Your Age is </b>
</td>
<td>
<input class="resform" type="text" readonly="" size="36" name="val">
</td>
</tr>
<tr>
<td>
<b> Your Age in Days </b>
</td>
<td>
<input class="resform" type="text" readonly="" size="36" name="val1">
</td>
</tr>
<tr>
<td>
<b> Your Age in Hours </b>
</td>
<td>
<input class="resform" type="text" readonly="" size="36" name="val2">
(Approximate)
</td>
</tr>
<tr>
<td class="form">
<b> Your Age in Minutes </b>
</td>
<td>
<input class="resform" type="text" readonly="" size="36" name="val3">
(Approximate)
</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>
<b> Your Next Birthday</b>
</td>
<td>
<input class="innerc resform" type="text" readonly="" size="36" name="val4">
</td>
</tr>
</tbody>
</table>
</form>
</td>
</tr>
</tbody>
</table>
<br>
</td>
<td> </td>
</tr>
<tr>
<td align="right" colspan="2"> </td>
<td> </td>
</tr>
</tbody>
</table>
</div>
<br>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
There's a number of ways to achieve what you're asking.
For the formatting, you could define CSS rules for the table to be something like:
width: 100%;
text-align: center;
For the time until the 50th birthday, you could add 50 years in ms to the birth date and calculate accordingly, however you might need to be aware of the following in your calculations:
https://en.wikipedia.org/wiki/Year_2038_problem

How to fix counter not showing correct value as well as resetting with new string

Here's a jsfiddle: https://jsfiddle.net/m6vxgg0m/15/
The console log shows the output.
I've been trying to get the number of occurrences of a string in an array using jQuery. The loop I'm using to check if the string value is present in each index of the array appears to be correct. I'm not sure why it isn't working correctly. I never get the correct counter value. If I keep the string in the text field and I keep hitting enter, the counter keeps increasing even though I set the counter back to 0 right inside the keyup event. If there are two occurrences of a string in the array, the counter should always display the value of 2. But it doesn't. Very frustrated.
JS:
$(function(){ keywordSearchFeature() });
function keywordSearchFeature(){
// Selector Variables
var inputSel = $('#search-term');
var noticeLblSel = $('.searchInstance');
var contentSel = $('.RadGrid.RadGrid_Default.mydatagrid .rgMasterTable tr');
// Functional Variables
var keywordVal;
var keywordValL; // keywordVal lowercase
var keyCounter = 0; // counter
var cellValues = []; //
var cellValuesL = []; // cellValues lowercase
// Type keyword
inputSel.on('keyup', function(e){
// Reset Counter
keyCounter = 0;
// Keyword Value
keywordVal = $(this).val();
// Keyword Lowercase Value
keywordValL = keywordVal.toLowerCase();
// console.log(keywordValL);
// Clear notice label when retyping
noticeLblSel.text('');
// Enter Key
if (e.which == 13) {
if(keywordValL != null && keywordValL != '' && keywordValL.length > 3){
console.log('ENTER KEY CLICKED: Value entered is: ' + keywordValL);
// Store content in arraykeyinstances[]
contentSel.each(function(i,tr){
var tdLines = $('td',tr).map(function(i,td){
// Get each cell string, and trim whitespace
var tdCellContent = $(td).text().trim();
// console.log(tdCellContent);
// Push each cell value to array
cellValues.push(tdCellContent);
cellValuesL.push(tdCellContent.toLowerCase());
});
});
// console.log(cellValues);
console.log(cellValuesL);
for (var i = 0; i < cellValuesL.length; i++) {
if (cellValuesL[i] == keywordValL) {
keyCounter++;
}
}
console.log(keyCounter);
// Notice label text
if(keyCounter > 0) {
noticeLblSel.text('Instance 1 of ' + keyCounter + ' found on this page.');
} else {
noticeLblSel.text('No instances for "' + keywordVal + '" found.');
}
} else {
noticeLblSel.text('Please enter 4 or more characters.');
}
}
});
// Click Events
//$(document).on('click','.btn-searchnext',function(){});
//$(document).on('click','.btn-searchprev',function(){});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="formholder searchkeywordholder">
<div class="form_inner">
<div class="formrow form-col-1" tabindex="0">
<div id="find-in-page">
<div class="fielditem searchfielditem">
<input type="text"
id="search-term"
placeholder="Type in the phrase to search and click Next..."
title="Enter Search Phrase"
class="text searchfield"
aria-label="Search Keyword Field" />
<button id="next"
class="button bttn-clear btn-searchnext"
title="Next"
aria-label="Search Next Button">
Next
</button>
<button id="prev"
class="button bttn-find btn-searchprev"
title="Previous"
aria-label="Search Previous Button">
Previous
</button>
</div>
<label id="labelResult" class="searchInstance"></label>
</div>
</div>
</div>
</div>
<div class="RadGrid RadGrid_Default mydatagrid staticheaders nostripes" id="ctl00_MainContent_customProjectAssets_gridItems" tabindex="0">
<div class="rgDataDiv" id="ctl00_MainContent_customProjectAssets_gridItems_GridData">
<table class="rgMasterTable rgClipCells rgClipCells" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00">
<tbody>
<tr class="groupinghighlight" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00__0">
<td valign="middle">
<div>
</div>
</td>
<td>
<div>
<div>
<div id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl04_divChildAssetStyle">
Antenna B1
</div>
</div>
</div>
</td>
<td>
Equipment and Materials
</td>
<td>
C2 Equipment
</td>
<td>
Antenna
</td>
<td>
Basic
</td>
<td>
B1
</td>
<td>
<div class="rating_general rating_yellow" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl04_divRating" title="Asset's Rate">
0.36
</div>
</td>
<td align="center">
<span class="aspNetDisabled"><input disabled="disabled" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl04_checkboxOverride" name="ctl00$MainContent$customProjectAssets$gridItems$ctl00$ctl04$checkboxOverride" type="checkbox"></span>
</td>
<td>
<span id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl04_spanAssetTag" title="Incident Response/Recovery">IRR</span>
</td>
<td align="center">
<span id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl04_spanClassificationLevel" title="UNCLASSIFIED">U</span>
</td>
<td align="center">
<input id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl04_checkboxDelete" name="ctl00$MainContent$customProjectAssets$gridItems$ctl00$ctl04$checkboxDelete" onclick="$.onCheckDeleteChange('0');" type="checkbox">
</td>
</tr>
<tr class="groupinghighlight" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00__1">
<td valign="middle">
<div>
</div>
</td>
<td>
<div>
<div style="width: 200px; margin: 0 auto;">
<div id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl05_divChildAssetStyle">
Content 1
</div>
</div>
</div>
</td>
<td>
This is content
</td>
<td>
My text
</td>
<td>
lorem ipsum dolor
</td>
<td>
sit amet
</td>
<td></td>
<td>
<div class="rating_general rating_orange" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl05_divRating" title="Asset's Rate">
0.56
</div>
</td>
<td align="center">
<span class="aspNetDisabled"><input disabled="disabled" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl05_checkboxOverride" name="ctl00$MainContent$customProjectAssets$gridItems$ctl00$ctl05$checkboxOverride" type="checkbox"></span>
</td>
<td>
<span id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl05_spanAssetTag" title="No Asset Tag Assigned"></span>
</td>
<td align="center">
<span id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl05_spanClassificationLevel" title="UNCLASSIFIED">U</span>
</td>
<td align="center">
<input id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl05_checkboxDelete" name="ctl00$MainContent$customProjectAssets$gridItems$ctl00$ctl05$checkboxDelete" onclick="$.onCheckDeleteChange('1');" type="checkbox">
</td>
</tr>
<tr class="rgRow" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00__2">
<td valign="middle">
<div>
</div>
</td>
<td>
<div>
<div style="width: 200px; margin: 0 auto;">
<div class="iconGridSubordinateArrow" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_divChildArrowImage" style="float: left; width: 17px;"></div>
<div id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_divChildAssetStyle" style="float: left; width: 180px;">
equivalent
</div>
</div>
</div>
</td>
<td>
People
</td>
<td>
Individuals
</td>
<td>
lorem
</td>
<td>
ipsum
</td>
<td></td>
<td>
<div class="rating_general rating_yellow" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_divRating" title="Asset's Rate">
0.44
</div>
</td>
<td align="center">
<span class="aspNetDisabled"><input disabled="disabled" id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_checkboxOverride" name="ctl00$MainContent$customProjectAssets$gridItems$ctl00$ctl06$checkboxOverride" type="checkbox"></span>
</td>
<td>
<span id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_spanAssetTag" title="No Asset Tag Assigned"></span>
</td>
<td align="center">
<span id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_spanClassificationLevel" title="UNCLASSIFIED">U</span>
</td>
<td align="center">
<input id="ctl00_MainContent_customProjectAssets_gridItems_ctl00_ctl06_checkboxDelete" name="ctl00$MainContent$customProjectAssets$gridItems$ctl00$ctl06$checkboxDelete" onclick="$.onCheckDeleteChange('2');" type="checkbox">
</td>
</tr>
</tbody>
</table>
</div>
</div>
First, the reason that your keyCounter increases each time you hit enter is because you do not reset cellValuesL to an empty array in your keyup event handler. This means that after the first time you hit enter, the contentSel table is parsed and 36 text values are pushed onto cellValuesL. The next time you hit enter, contentSel is parsed again and the same 36 values are again pushed onto cellValuesL so that cellValuesL.length is now 72. The same 36 values get pushed onto cellValuesL each time you hit the enter key.
One way you can fix this is by moving var cellValuesL = []; to inside the keyup event handler. However, a better solution is to move the code that builds the cellValuesL array (contentSel.each) to outside of the keyup event handler. As the text values in the table never change, it does not make sense to keep fetching the texts from the table and building a new array each time the user presses the enter key.
To your second point about having two occurrences of a string in your cellValuesL array, I think you must be confused about what your code is checking. Your code loops through each value in cellValuesL and for each element in that array that equals the lower-cased user input, keyCounter is incremented. In your example, no two elements in cellValuesL are equal, so it is not possible for the loop to ever produce more than one match. What I assume you must want to is to check whether each element in cellValuesL contains the lower-cased user input. If this is the desired behavior, you will need to update your conditional to the following:
for (var i = 0; i < cellValuesL.length; i++) {
if (cellValuesL[i].indexOf(keywordValL) > -1) {
keyCounter++;
}
}
A more modern and elegant way of achieving the same thing as the code above would be to use Array.prototype.filter and an Arrow Function:
keyCounter = cellValuesL.filter(val => val.indexOf(keywordValL) > -1).length;
Finally, I want to suggest that your JavaScript code can be cleaned-up quite a bit. Here is an example that doesn't use any ES6 language features:
$(function () {
var inputSel = $('#search-term');
var contentSel = $('.RadGrid.RadGrid_Default.mydatagrid .rgMasterTable tr');
var noticeLblSel = $('.searchInstance');
var cellValuesL = $('td', contentSel).map(function () {
return $(this).text().trim().toLowerCase();
}).get();
inputSel.on('keyup', function (e) {
noticeLblSel.text('');
if (e.which !== 13) { return; }
var keywordVal = $(this).val();
var keywordValL = keywordVal.toLowerCase();
if (!keywordValL || keywordValL.length <= 3) {
noticeLblSel.text('Please enter 4 or more characters.');
return;
}
var keyCounter = cellValuesL.filter(function (val) {
return val.indexOf(keywordValL) > -1;
}).length;
if (keyCounter > 0) {
noticeLblSel.text('Instance 1 of ' + keyCounter + ' found on this page.');
} else {
noticeLblSel.text('No instances for "' + keywordVal + '" found.');
}
});
});
I have also created an example fiddle.

How to read an array of integers from an element to get values from it?

I make a code , that randomly display an 6-item array in a div.
i want to read the array and pass it to function to calculate the mean of it?
HTML
what i must do , how can i store the data of div(id="numbers" )
and push it in array ?
<pre>
<div >
<form action="" method="post" name="meanForm" onsubmit='return false' id="formmine">
<table width="100%" border="0"
<tr>
<td colspan="3" style="background-color:#06F ;color:#FFF">Answer this problem</td>
</tr>
<tr>
<td style="color:green; font-size:20px">What is the mean of these numbers </td>
<td colspan="2" ><div id="numbers"></div>
</td>
</tr>
<tr>
<td colspan="3"> </td>
</tr>
<tr id="answerANDpic">
<td height="62" colspan="3" align="center" > <input name="" type="text" size="15" maxlength="100" height="50" style=" border: solid #0C0 ; border-width:thin" id="answer" onkeydown="searchm(this)"/> </td>
</tr>
<tr>
<td colspan="3" ><div id ="explain" ></div></td>
</tr>
<tr>
<td> </td>
<td><input name="" type="button" id="newEx" style="background-color:green ; color:white" align ="left" value="New Problem" class="send_feed" onclick="randomArray(6,0,99)" /></td>
<td><input name="" type="button" id="solution" style="background-color:#606 ; color:#FFF " align="left" class="send_feed" value="Solution" onclick="solution()"/></td>
</tr>
</table>
</form>
</div>
in JS
var myNumArray = randomArray(6,0,99);
function random_number(min,max) {
return (Math.round((max-min) * Math.random() + min));
}
function randomArray(num_elements,min,max) {
var nums = new Array;
for (var element=0; element<num_elements; element++) {
nums[element] = random_number(min,max);
}
document.getElementById("numbers").innerHTML=nums;
calcMean(nums);
}
function calcMean(nums) {
var num=0;
for (var i=0;i<nums.length;i++) {
num += parseFloat( nums[i], 6 );
}
var divide=num/nums.length;
var mean=(parseInt(divide,10));
var maxi = Math.max.apply(Math,nums);
var mini = Math.min.apply(Math,nums);
return mean,maxi,mini;
}
function searchm(ele) {
if(event.keyCode == 13) {
// alert(ele.value); // i get the value and put it on alert
var inans= ele.value;
return inans;
}
}
function soltuion(){
//read array saved in div id="numbers"
// call calcMean()
//get the mean and max min values
}
See comments in code below. Your code is not far off working.
function calcMean(nums){
var num=0;
for (var i=0;i<nums.length;i++){
// parseFloat only has one argument
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat
num += parseFloat( nums[i])
// If the numbers in the nums array
// are already floats, you don't need parseFloat
// So maybe you can do... ?
// num += nums[i]
}
// The line below might divide by zero, so check
if (nums.length == 0) {
return 0;
}
var divide=num/nums.length;
// No need to reparse a number.
mean=divide
// This code suggests that nums is already filled with numbers
// See comment in for-loop above
var maxi = Math.max.apply(Math,nums);
var mini = Math.min.apply(Math,nums);
// This returns all 3 numbers
return [mean,mini,maxi];
// If you want just the mean,
// return mean;
}

Pass a field calculation in html to another field in the SAME form

So, I can only find how to pass the information to another page not the same page and this has to be done entirely on the client side, no server side work as there will be no internet connection when this is used, hence the mailto for the form data so it can be sent when a connection is available.
Basically I have two tables, one on the left that has a standard set of numbers (fields time1-time8) that the user can change if need be. These values total into the 'designhours' field. That number must be put into the 'designhours' field on the right side for the various calculations needed there. In my former work (not HTML or javascript) if the field name was the same the data was passed, obviously not the case here.
Before I put the table on the left in, this form worked beautifully, but now I need to add the option of totaling a new 'designhours' value. Many thanks to those that have helped me before and many thanks to anyone that helps now. I am still learning, but I am getting there.
Sample code with most fields removed so you can see what I am doing (thanks for pointing out) Full code way below...
So the field names in the left table
time1 - time8
those values are added to put the total in designhours
And the right table
wage, instructors, class, designhours (which is the same as in the left table), cost, many, atetextfield7, build_cost, buy_cost, build_hours, buy_hours, build_train, buy_train, build_total, buy_total
<script type="text/javascript">
var btn = document.getElementById('calculate');
btn.onclick = function() {
var wageval = parseInt(document.getElementById('wage').value) || 0;
var instructorsval = parseInt(document.getElementById('instructors').value) || 0;
var build_cost = document.getElementById('build_cost');
var buy_cost = document.getElementById('buy_cost');
var msg = [];
if (isNaN(wageval)) {
msg.push('Average instructor hourly wage is not a number');
// the value isn't a number
}
if (isNaN(instructorsval)) {
msg.push('Number of instructors per course is not a number');
// the value isn't a number
}
if (msg.length > 0)   {
build_cost.value = msg.join(', ');
buy_cost.value = msg.join(', ');
and the calculations below:
} else {
designhours.value = (time1 + time2 + time3 + time4 + time5 + time6 + time7 + time8);
build_cost.value = (wageval * designhoursval);
buy_cost.value = (costval * hiddenval);
build_hours.value = (designhoursval * manyval);
build_train.value = (classval * hiddenval);
build_total.value = (wageval * designhoursval * manyval + classval);
buy_total.value = (costval * manyval);
var build_costval = parseInt(build_cost.value) || 0;
var buy_costval = parseInt(buy_cost.value) || 0;
var build_hoursval = parseInt(build_hours.value) || 0;
var build_trainval = parseInt(build_train.value) || 0;
var build_totalval = parseInt(build_total.value) || 0;
var buy_totalval = parseInt(buy_total.value) || 0;
var designhoursval = parseInt(designhours.value) || 0;
}
Full Code below
HTML
<form id="form1" name="form1" method="post" action="mailto:?subject=Laerdal%20ROI%20Information" enctype="text/plain">
<table width="859" border="0" cellpadding="0" cellspacing="0">
<tr>
<td valign="bottom">
<table width="352" border="0" cellspacing="0" cellpadding="0">
<tr>
<td height="22" colspan="2"> </td>
</tr>
<tr>
<td width="225" height="22"> </td>
<td width="127" height="22" align="left"> </td>
</tr>
<tr>
<td height="22"><span class="norm">Needs Analysis</span></td>
<td height="22" align="center"><input name="time1" type="text" class="field" id="time1" value="1" size="10" /></td>
</tr>
<tr>
<td height="22"><span class="norm">Research</span></td>
<td height="22" align="center"><input name="time2" type="text" class="field" id="time2" value="2" size="10" /></td>
</tr>
<tr>
<td height="22"><span class="norm">Design</span></td>
<td height="22" align="center"><input name="time3" type="text" class="field" id="time3" value="2" size="10" /></td>
</tr>
<tr>
<td height="22"><span class="norm">Scenario Programming</span></td>
<td height="22" align="center"><input name="time4" type="text" class="field" id="time4" value="3" size="10" /></td>
</tr>
<tr>
<td height="22"><span class="norm">Support Materials</span></td>
<td height="22" align="center"><input name="time5" type="text" class="field" id="time5" value="16" size="10" /></td>
</tr>
<tr>
<td height="22"><span class="norm">Validation</span></td>
<td height="22" align="center"><input name="time6" type="text" class="field" id="time6" value="2" size="10" /></td>
</tr>
<tr>
<td height="22"><span class="norm">Revision</span></td>
<td height="22" align="center"><input name="time7" type="text" class="field" id="time7" value="4" size="10" /></td>
</tr>
<tr>
<td height="22"><span class="norm">Implementation</span></td>
<td height="22" align="center"><input name="time8" type="text" class="field" id="time8" value="2" size="10" /></td>
</tr>
<tr>
<td height="22"><span class="norm">Total</span></td>
<td height="22" align="center"><input name="designhours" class="field" type="text" id="designhours" size="10" /></td>
</tr>
<tr>
<td height="73" colspan="2"> </td>
</tr>
</table>
<p> </p></td>
<td width="55" valign="bottom"> </td>
<td>
<table width="440" border="0" cellspacing="0" cellpadding="0">
<tr>
<td height="36" colspan="2" align="right" class="norm">Average Instructor hourly wage:</td>
<td height="36" align="right"><input name="wage" class="field" type="text" id="wage" size="12" /></td>
</tr>
<tr>
<td height="36" colspan="2" align="right" class="norm">Number of Instructors per course:</td>
<td height="36" align="right"><input name="instructors" class="field" type="text" id="instructors" size="12" /></td>
</tr>
<tr>
<td height="36" colspan="2" align="right" class="norm">Scenario Programing Class:</td>
<td height="36" align="right"><input name="class" class="field" type="text" id="class" size="12" /></td>
</tr>
<tr>
<td height="36" colspan="2" align="right" class="norm">Instruction design hours per scenarios:</td>
<td height="36" align="right"><input name="designhours" class="field" type="text" readonly="true" id="designhours" size="12" /></td>
</tr>
<tr>
<td height="36" colspan="2" align="right" class="norm">Average cost of SimStore Scenarios:</td>
<td height="36" align="right"><input name="cost" class="field" type="text" id="cost" value="295" size="12" /></td>
</tr>
<tr>
<td height="36" colspan="2" align="right" class="norm">How many scenarios do you need:</td>
<td height="36" align="right"><input name="many" class="field" type="text" id="many" size="12" /></td>
</tr>
<tr>
<td height="36" colspan="2" align="right" class="norm">Date needed?:</td>
<td height="36" align="right"><input name="atetextfield7" class="field" type="text" id="atetextfield7" size="12" /></td>
</tr>
<tr>
<td height="40" colspan="3" align="center" class="calc">CALCULATED RESULTS</td>
</tr>
<tr>
<td height="40"><input name="hidden" type="hidden" id="hidden" value="1" /></td>
<td height="40" align="center" class="bold">BUILD</td>
<td height="40" align="center" class="bold">BUY</td>
</tr>
<tr>
<td height="38" align="right" class="norm">Cost per scenario:<img src="images/Blank.png" alt="" width="12" height="5" /></td>
<td height="38" align="center"><input name="build_cost" class="field" type="text" id="build_cost" size="12" /></td>
<td height="38" align="center"><input name="buy_cost" class="field" type="text" id="buy_cost" size="12" /></td>
</tr>
<tr>
<td height="38" align="right" class="norm">Total development hours:<img src="images/Blank.png" alt="" width="12" height="5" /></td>
<td height="38" align="center"><input name="build_hours" class="field" type="text" id="build_hours" size="12" /></td>
<td height="38" align="center"><input name="buy_hours" class="field" type="text" id="buy_hours" value="0" size="12" /></td>
</tr>
<tr>
<td height="38" align="right" class="norm">
Scenario Programming<img src="images/Blank.png" alt="" width="12" height="5" /><br />
Training (8h):<img src="Blank.png" alt="" width="12" height="5" />
</td>
<td height="38" align="center"><input name="build_train" class="field" type="text" id="build_train" size="12" /></td>
<td height="38" align="center"><input name="buy_train" class="field" type="text" id="buy_train" value="0" size="12" /></td>
</tr>
<tr>
<td height="38" align="right" class="norm">Total Cost:<img src="images/Blank.png" alt="" width="12" height="5" /></td>
<td height="38" align="center"><input name="build_total" class="field" type="text" id="build_total" size="12" /></td>
<td height="38" align="center"><input name="buy_total" class="field" type="text" id="buy_total" size="12" /></td>
</tr>
<tr>
<td height="50" colspan="3" align="center" valign="bottom"><input type="reset" />
<img src="images/Blank.png" alt="" width="15" height="25" />
<input name="calculate" type="button" id="calculate" value="Calculate" />
<img src="images/Blank.png" alt="" width="15" height="25" />
<input name="share" type="submit" id="submit" value="Share" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
Javascript
var btn = document.getElementById('calculate');
btn.onclick = function () {
//get the input values
var wageval = parseInt(document.getElementById('wage').value) || 0;
var instructorsval = parseInt(document.getElementById('instructors').value) || 0;
var classval = parseInt(document.getElementById('class').value) || 0;
var designhoursval = parseInt(document.getElementById('designhours').value) || 0;
var costval = parseInt(document.getElementById('cost').value) || 0;
var manyval = parseInt(document.getElementById('many').value) || 0;
var hiddenval = parseInt(document.getElementById('hidden').value) || 0;
var time1val = parseInt(document.getElementById('time1').value) || 0;
var time2val = parseInt(document.getElementById('time2').value) || 0;
var time3val = parseInt(document.getElementById('time3').value) || 0;
var time4val = parseInt(document.getElementById('time4').value) || 0;
var time5val = parseInt(document.getElementById('time5').value) || 0;
var time6val = parseInt(document.getElementById('time6').value) || 0;
var time7val = parseInt(document.getElementById('time7').value) || 0;
var time8val = parseInt(document.getElementById('time8').value) || 0;
// get the elements to hold the results
var build_cost = document.getElementById('build_cost');
var buy_cost = document.getElementById('buy_cost');
var build_hours = document.getElementById('build_hours');
var buy_hours = document.getElementById('buy_hours');
var build_total = document.getElementById('build_total');
var build_train = document.getElementById('build_train');
var buy_total = document.getElementById('buy_total');
var time1 = document.getElementById('time1');
var time2 = document.getElementById('time1');
var time3 = document.getElementById('time1');
var time4 = document.getElementById('time1');
var time5 = document.getElementById('time1');
var time6 = document.getElementById('time1');
var time7 = document.getElementById('time1');
var time8 = document.getElementById('time1');
var designhours = document.getElementById('designhours');
// create an empty array to hold error messages
var msg = [];
// check each input value, and add an error message to the array if it's not a number
if (isNaN(wageval)) {
msg.push('Average instructor hourly wage is not a number');
// the value isn't a number
}
if (isNaN(instructorsval)) {
msg.push('Number of instructors per course is not a number');
// the value isn't a number
}
if (isNaN(classval)) {
msg.push('Scenario programming class is not a number');
// the value isn't a number
}
if (isNaN(designhoursval)) {
msg.push('Instruction design hours per scenario is not a number');
// the value isn't a number
}
if (isNaN(costval)) {
msg.push('Average cost of SimStore scenarios is not a number');
// the value isn't a number
}
if (isNaN(manyval)) {
msg.push('How many scenarios do you need is not a number');
// the value isn't a number
}
if (isNaN(hiddenval)) {
msg.push('joe messed up');
// the value isn't a number
}
if (isNaN(time1val)) {
msg.push('Needs Analysis is not a number');
// the value isn't a number
}
if (isNaN(time2val)) {
msg.push('Research is not a number');
// the value isn't a number
}
if (isNaN(time3val)) {
msg.push('Design is not a number');
// the value isn't a number
}
if (isNaN(time4val)) {
msg.push('Scenario Programming is not a number');
// the value isn't a number
}
if (isNaN(time5val)) {
msg.push('Support Materials is not a number');
// the value isn't a number
}
if (isNaN(time6val)) {
msg.push('Validation is not a number');
// the value isn't a number
}
if (isNaN(time7val)) {
msg.push('Revision is not a number');
// the value isn't a number
}
if (isNaN(time8val)) {
msg.push('Implementation is not a number');
// the value isn't a number
}
// if the array contains any values, display an error message
if (msg.length > 0)  {
build_cost.value = msg.join(', ');
buy_cost.value = msg.join(', ');
build_hours.value = msg.join(', ');
build_train.value = msg.join(', ');
build_total.value = msg.join(', ');
buy_total.value = msg.join(', ');
time1.value = msg.join(', ');
time2.value = msg.join(', ');
time3.value = msg.join(', ');
time4.value = msg.join(', ');
time5.value = msg.join(', ');
time6.value = msg.join(', ');
time7.value = msg.join(', ');
time8.value = msg.join(', ');
} else {
designhours.value = (time1 + time2 + time3 + time4 + time5 + time6 + time7 + time8);
build_cost.value = (wageval * designhoursval);
buy_cost.value = (costval * hiddenval);
build_hours.value = (designhoursval * manyval);
build_train.value = (classval * hiddenval);
build_total.value = (wageval * designhoursval * manyval + classval);
buy_total.value = (costval * manyval);
var build_costval = parseInt(build_cost.value) || 0;
var buy_costval = parseInt(buy_cost.value) || 0;
var build_hoursval = parseInt(build_hours.value) || 0;
var build_trainval = parseInt(build_train.value) || 0;
var build_totalval = parseInt(build_total.value) || 0;
var buy_totalval = parseInt(buy_total.value) || 0;
var designhoursval = parseInt(designhours.value) || 0;
}
};
Thanks again for any guidance anyone can give. I'm struggling through all of this.
First of all, no idea what these are for:
var time1 = document.getElementById('time1');
var time2 = document.getElementById('time1');
var time3 = document.getElementById('time1');
var time4 = document.getElementById('time1');
var time5 = document.getElementById('time1');
var time6 = document.getElementById('time1');
var time7 = document.getElementById('time1');
var time8 = document.getElementById('time1');
Then, you only have the element as var in timex.
So the simplest fix is:
designhours.value = time1val + time2val + time3val + time4val + time5val + time6val + time7val + time8val;
instead of:
designhours.value = time1 + time2 + time3 + time4 + time5 + time8 + time7 + time8;
See where you went wrong? You were adding objects (the input fields) together, not their values (that you already had to begin with).
And note, digits in a input field are not numbers but a string.
You also might want to specify a radix with parseInt like parseInt(val,10);
Finally you could re-factor the code quite a bit, this is indeed a bit much (but good on ya for providing useful error-detection).
See this fiddle: http://jsfiddle.net/4nHvc/1/
UPDATE: upon further inspection there is a lot more wrong:
Why are these function local variables set at the end of your function?
var build_costval = parseInt(build_cost.value) || 0;
var buy_costval = parseInt(buy_cost.value) || 0;
var build_hoursval = parseInt(build_hours.value) || 0;
var build_trainval = parseInt(build_train.value) || 0;
var build_totalval = parseInt(build_total.value) || 0;
var buy_totalval = parseInt(buy_total.value) || 0;
var designhoursval = parseInt(designhours.value) || 0;
The very next line of javascript after the first one where you used the wrong variable names (thus adding objects instead of their values) can't work then either:
build_cost.value = (wageval * designhoursval);
Well, if you get the value of the inputfield designhoursval at the start of the code, that field is still empty.. So then when the script executes the above line, what is designhoursval ??? right, empty. If for instance you re-read that value using the last block of 'useless' code WITHOUT the var variable declaration (you declared it already at the start of your function) and place it above that line, then another field of your calculator starts to work:
designhoursval = parseInt(designhours.value) || 0;
build_cost.value = (wageval * designhoursval);
But then.. isn't it easier to first get al the input-values, do the math, then output the values?
See this fiddle, now it almost works: http://jsfiddle.net/4nHvc/2/
update your time values...
var time1 = parseInt(document.getElementById('time1').value);
var time2 = parseInt(document.getElementById('time1').value);
var time3 = parseInt(document.getElementById('time1').value);
var time4 = parseInt(document.getElementById('time1').value);
var time5 = parseInt(document.getElementById('time1').value);
var time6 = parseInt(document.getElementById('time1').value);
var time7 = parseInt(document.getElementById('time1').value);
var time8 = parseInt(document.getElementById('time1').value);
Also, I'm not sure how you wired up your button to your script, so I changed your function...
function doThis() {
and your button...
<input name="calculate" type="button" id="calculate" value="Calculate" onclick="doThis()" />
Those may have been fine in your code, but that part was omitted in your post so check it out. (You can just use an "alert('foo');" to check.)

Categories

Resources