Too much recursion - radio button - jquery - javascript

I have a dynamic form and in that many fields I want to be autocalculated when user goes on with the form. In the form I have 2 radio button mrp and rate. By default mrp is selected. If user doesn't change the default button selected, the value totalCst will be calculated as qty*mrp*cstpercent of all the rows.
If user selects rate radiobutton the value will be calculated as qty*rate*cstpercent of all the rows. I'll add the onchange event later. First I want to get the value totalCst calculated on mrp only or rate whichever is selected.
Radio Button code -
<div class="form-group pull-right">
<label class="radio-inline"><input type="radio" name="taxon" id="mrp" value="mrp" checked="checked">MRP</label>
<label class="radio-inline"><input type="radio" name="taxon" id="rate" value="rate">Rate</label>
</div>
JS
<?php
/* start getting the total amount */
$this->registerJs('
function getSum() {
var sum = 0;
var totalDiscount = 0;
var totalMrp = 0;
var totalCst = 0;
var totalWbst = 0;
var totalCstonamount = 0;
var totalWbstonamount = 0;
var totalCstonmrp = 0;
var totalWbstonmrp = 0;
var cstperValue = $(".cstPercent").val();
var wbstperValue = $(".wbstPercent").val();
var selectedValue = $("input[name=taxon]:checked").val();
alert(selectedValue);
var items = $(".item");
items.each(function (index, elem) {
var qtyValue = $(elem).find(".qty").val();
var rateValue = $(elem).find(".rate").val();
var discValue = $(elem).find(".disc").val();
var mrpValue = $(elem).find(".mrp").val();
var freeValue = $(elem).find(".free").val();
sum = (parseFloat(sum) + (parseFloat(qtyValue) * parseFloat(rateValue))).toFixed(2);
totalDiscount = (parseFloat(totalDiscount) + ((parseFloat(qtyValue) * parseFloat(rateValue) * parseFloat(discValue))/100)).toFixed(2);
totalMrp = (parseFloat(totalMrp) + ((parseFloat(qtyValue) + parseFloat(freeValue)) * parseFloat(mrpValue))).toFixed(2);
totalCstonamount = (parseFloat(totalCst) + ((parseFloat(qtyValue) * parseFloat(rateValue)) * parseFloat(cstperValue))/100).toFixed(2);
totalWbstonamount = (parseFloat(totalWbst) + ((parseFloat(qtyValue) * parseFloat(rateValue)) * parseFloat(wbstperValue))/100).toFixed(2);
totalCstonmrp = (parseFloat(totalCst) + (((parseFloat(qtyValue) + parseFloat(freeValue)) * parseFloat(mrpValue)) * parseFloat(cstperValue))/100).toFixed(2);
totalWbstonmrp = (parseFloat(totalWbst) + (((parseFloat(qtyValue) + parseFloat(freeValue)) * parseFloat(mrpValue)) * parseFloat(wbstperValue))/100).toFixed(2);
});
if(isNaN(sum) || sum.length == 0) {
sum = 0;
}
if(isNaN(totalDiscount) || totalDiscount.length == 0) {
totalDiscount = 0;
}
if(isNaN(totalMrp) || totalMrp.length == 0) {
totalMrp = 0;
}
if(isNaN(totalCstonamount) || totalCstonamount.length == 0) {
totalCstonamount = 0;
}
if(isNaN(totalWbstonamount) || totalWbstonamount.length == 0) {
totalWbstonamount = 0;
}
if(isNaN(totalCstonmrp) || totalCstonmrp.length == 0) {
totalCstonmrp = 0;
}
if(isNaN(totalWbstonmrp) || totalWbstonmrp.length == 0) {
totalWbstonmrp = 0;
}
$(".sum").val(sum);
$(".totalDiscount").val(totalDiscount);
$(".totalMrp").val(totalMrp);
if (selectedValue == "mrp") {
getSum();
$(".totalCst").val(totalCstonmrp);
}
else if (selectedValue == "rate") {
getSum();
$(".totalCst").val(totalCstonamount);
}
}
$(".container-items").on("change", function() {
getSum();
});
$(".cstPercent").on("change", function() {
getSum();
});
$(".wbstPercent").on("change", function() {
getSum();
});
jQuery(".dynamicform_wrapper").on("afterDelete", function(e) {
getSum();
});
');
/*end getting the total amount */
?>
I'm getting the value selected in alert but too many popup and getting error -
Too much recursion
Updated JS
<?php
/* start getting the total amount */
$this->registerJs('
var totalCstonamount = 0;
var totalWbstonamount = 0;
var totalCstonmrp = 0;
var totalWbstonmrp = 0;
function getSum() {
var sum = 0;
var totalDiscount = 0;
var totalMrp = 0;
var totalCst = 0;
var totalWbst = 0;
// var totalCstonamount = 0;
// var totalWbstonamount = 0;
// var totalCstonmrp = 0;
// var totalWbstonmrp = 0;
var cstperValue = $(".cstPercent").val();
var wbstperValue = $(".wbstPercent").val();
//var selectedValue = $("input[name=taxon]:checked").val();
//alert(selectedValue);
var items = $(".item");
items.each(function (index, elem) {
var qtyValue = $(elem).find(".qty").val();
var rateValue = $(elem).find(".rate").val();
var discValue = $(elem).find(".disc").val();
var mrpValue = $(elem).find(".mrp").val();
var freeValue = $(elem).find(".free").val();
sum = (parseFloat(sum) + (parseFloat(qtyValue) * parseFloat(rateValue))).toFixed(2);
totalDiscount = (parseFloat(totalDiscount) + ((parseFloat(qtyValue) * parseFloat(rateValue) * parseFloat(discValue))/100)).toFixed(2);
totalMrp = (parseFloat(totalMrp) + ((parseFloat(qtyValue) + parseFloat(freeValue)) * parseFloat(mrpValue))).toFixed(2);
totalCstonamount = (parseFloat(totalCst) + ((parseFloat(qtyValue) * parseFloat(rateValue)) * parseFloat(cstperValue))/100).toFixed(2);
totalWbstonamount = (parseFloat(totalWbst) + ((parseFloat(qtyValue) * parseFloat(rateValue)) * parseFloat(wbstperValue))/100).toFixed(2);
totalCstonmrp = (parseFloat(totalCst) + (((parseFloat(qtyValue) + parseFloat(freeValue)) * parseFloat(mrpValue)) * parseFloat(cstperValue))/100).toFixed(2);
totalWbstonmrp = (parseFloat(totalWbst) + (((parseFloat(qtyValue) + parseFloat(freeValue)) * parseFloat(mrpValue)) * parseFloat(wbstperValue))/100).toFixed(2);
});
if(isNaN(sum) || sum.length == 0) {
sum = 0;
}
if(isNaN(totalDiscount) || totalDiscount.length == 0) {
totalDiscount = 0;
}
if(isNaN(totalMrp) || totalMrp.length == 0) {
totalMrp = 0;
}
if(isNaN(totalCstonamount) || totalCstonamount.length == 0) {
totalCstonamount = 0;
}
if(isNaN(totalWbstonamount) || totalWbstonamount.length == 0) {
totalWbstonamount = 0;
}
if(isNaN(totalCstonmrp) || totalCstonmrp.length == 0) {
totalCstonmrp = 0;
}
if(isNaN(totalWbstonmrp) || totalWbstonmrp.length == 0) {
totalWbstonmrp = 0;
}
$(".sum").val(sum);
$(".totalDiscount").val(totalDiscount);
$(".totalMrp").val(totalMrp);
// if (selectedValue == "mrp") {
// getSum();
// $(".totalCst").val(totalCstonmrp);
// }
// else if (selectedValue == "rate") {
// getSum();
// $(".totalCst").val(totalCstonamount);
// }
}
function getSumonclick(){
}
$(".container-items").on("change", function() {
getSum();
});
$(".cstPercent").on("change", function() {
getSum();
});
$(".wbstPercent").on("change", function() {
getSum();
});
getSum();
var selectedValue = $("input[name=taxon]:checked").val();
// var totalCstonamount = 200;
// var totalWbstonamount = 0;
// var totalCstonmrp = 100;
// var totalWbstonmrp = 0;
if (selectedValue == "mrp") {
getSum();
if(isNaN(totalCstonmrp) || totalCstonmrp.length == 0) {
totalCstonmrp = 0;
}
$(".totalCst").val(totalCstonmrp);
}
else if (selectedValue == "rate") {
getSum();
if(isNaN(totalCstonamount) || totalCstonamount.length == 0) {
totalCstonamount = 0;
}
$(".totalCst").val(totalCstonamount);
}
jQuery(".dynamicform_wrapper").on("afterDelete", function(e) {
getSum();
});
');
/*end getting the total amount */
?>
As per my understanding, Now the issue turns out to be to get the calculated values from inside of getSum function to outside of it.

First I want to get the value totalCst calculated on mrp only or rate
whichever is selected.
You can use the ternary operator here, rather than if... else...:
var factor = (factorMrp.checked ? 'mrp' : 'rate');
Working Example:
var factors = document.getElementById('factors');
var factorMrp = document.getElementById('mrp');
var factorRate = document.getElementById('rate');
var paragraph = document.getElementsByTagName('p')[0];
factorMrp.checked = true;
function checkFactor() {
var factor = (factorMrp.checked ? 'mrp' : 'rate');
paragraph.textContent = 'The value totalCst will be calculated as qty * ' + factor + ' * cstpercent of all the rows.';
}
factors.addEventListener('change',checkFactor,false);
window.addEventListener('load',checkFactor,false);
fieldset {
display: inline-block;
}
<form>
<fieldset id="factors">
<label class="radio-inline"><input type="radio" name="taxon" id="mrp" value="mrp" checked="checked">MRP</label>
<label class="radio-inline"><input type="radio" name="taxon" id="rate" value="rate">Rate</label>
</fieldset>
</form>
<p></p>

Related

Resetting InnerHTML

I've been looking at past submissions regarding this and haven't been able to find a solution that seems to work.
I have a simple form that calculates and then increments a value. The innerHTML output ("YourAmount") works fine the first time the form is submitted. However, if I resubmit the form with another amount, the original output flickers the old calculated results with the new one. How do I reset the innerHTML output?
Thanks!
// function for formatting numbers in currency format
function CurrencyFormatted(amount) {
var i = parseFloat(amount);
if (isNaN(i)) {
i = 0.00;
}
var minus = '';
if (i < 0) {
minus = '-';
}
i = Math.abs(i);
i = parseInt((i + .005) * 100);
i = i / 100;
s = new String(i);
if (s.indexOf('.') < 0) {
s += '.00';
}
if (s.indexOf('.') == (s.length - 2)) {
s += '0';
}
s = minus + s;
s = CommaFormatted(s)
return s;
}
// function for formatting numbers with embedded commas
function CommaFormatted(amount) {
var delimiter = ","; // replace comma if desired
var a = amount.split('.', 2)
var d = a[1];
var i = parseInt(a[0]);
if (isNaN(i)) {
return '';
}
var minus = '';
if (i < 0) {
minus = '-';
}
i = Math.abs(i);
var n = new String(i);
var a = [];
while (n.length > 3) {
var nn = n.substr(n.length - 3);
a.unshift(nn);
n = n.substr(0, n.length - 3);
}
if (n.length > 0) {
a.unshift(n);
}
n = a.join(delimiter);
if (d.length < 1) {
amount = n;
} else {
amount = n + '.' + d;
}
amount = minus + amount;
return amount;
}
function calculate() {
var NumStores = document.getElementById('NumStores').value;
var result = document.getElementById('result');
var baseProfit = NumStores * 50.00;
result.value = baseProfit;
var baseProfitOverYear = baseProfit * 360; // base profit (stores x cost) over 360 days
var result2 = document.getElementById('result2');
result2.value = baseProfitOverYear;
var amount = baseProfitOverYear; // load from server
var delay = 1000; // milliseconds
var incAmount = 20; // change to the amount by which you wish to increment
var tId = setInterval(function() {
document.getElementById("YourAmount").innerHTML = "$" + CurrencyFormatted(amount += incAmount);
}, delay)
}
// disable enter key
$(document).keypress(
function(event) {
if (event.which == '13') {
event.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="thisForm">
<input id="NumStores" type="number" required />
<input type="button" onClick="calculate()" value="Calculate">
</form>
<br><br>
<p id="YourAmount">Your Amount Is 0</p>
First, you should create a span tag within the paragraph tag to hold the value. Then make sure you only have one interval occurring at a time.
// Document elements and variables
var numStores = document.getElementById('num-stores'),
result = document.getElementById('result-1'),
result2 = document.getElementById('result-2'),
yourAmount = document.getElementById('your-amount'),
intervalId = null; // We need to rember this...
// Constants
var profitMargin = 50.00,
numberOfDays = 360,
incAmount = 20, // change to the amount by which you wish to increment
timerDelay = 1000; // milliseconds
function calculate() {
var inputValue = numStores.value;
var baseProfit = inputValue * profitMargin;
var baseProfitOverYear = baseProfit * numberOfDays; // base profit (stores x cost) over 360 days
var amount = baseProfitOverYear; // load from server
result.value = baseProfit;
result2.value = baseProfitOverYear;
clearInterval(intervalId); // Clear the GLOBAL interval, before we start a new one.
intervalId = setInterval(function() {
yourAmount.innerHTML = "$" + CurrencyFormatted(amount += incAmount);
}, timerDelay);
}
// Disable enter key
$(document).keypress(function(event) {
if (event.which == '13') {
event.preventDefault();
}
});
// function for formatting numbers in currency format
function CurrencyFormatted(amount) {
var i = parseFloat(amount);
if (isNaN(i)) {
i = 0.00;
}
var minus = '';
if (i < 0) {
minus = '-';
}
i = Math.abs(i);
i = parseInt((i + .005) * 100);
i = i / 100;
s = new String(i);
if (s.indexOf('.') < 0) {
s += '.00';
}
if (s.indexOf('.') == (s.length - 2)) {
s += '0';
}
s = minus + s;
s = CommaFormatted(s)
return s;
}
// function for formatting numbers with embedded commas
function CommaFormatted(amount) {
var delimiter = ","; // replace comma if desired
var a = amount.split('.', 2)
var d = a[1];
var i = parseInt(a[0]);
if (isNaN(i)) {
return '';
}
var minus = '';
if (i < 0) {
minus = '-';
}
i = Math.abs(i);
var n = new String(i);
var a = [];
while (n.length > 3) {
var nn = n.substr(n.length - 3);
a.unshift(nn);
n = n.substr(0, n.length - 3);
}
if (n.length > 0) {
a.unshift(n);
}
n = a.join(delimiter);
if (d.length < 1) {
amount = n;
} else {
amount = n + '.' + d;
}
amount = minus + amount;
return amount;
}
label { font-weight: bold; }
.input-field { display: block; }
.input-field label { display: inline-block; width: 7.667em;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="this-form">
<label>Number of Stores</label> <input id="num-stores" type="number" required />
<input type="button" onClick="calculate()" value="Calculate">
</form>
<br>
<p>Your amount is: <span id="your-amount">$0.00</span></p>
<div class="input-field"><label>Base Profit</label> <input type="text" id="result-1" /></div>
<div class="input-field"><label>Annual Profit</label> <input type="text" id="result-2" /></div>

balancing two input number fields but not showing values in fields in jquery

<!--js-->
function changeValue(dropdown,source) {
var option = dropdown.options[dropdown.selectedIndex].value;
if (option == '1' && source==0) {
var total = 20;
$("span").text(total);
$('.balance').attr({"min":0, "max":total}).on('input', function() {
var value = parseInt(this.value);
var otherInputs = $('.balance').not(this);
var remainderDiv;
var remainder, sum;
if (isNaN(value)) {
value = 0;
} else if (value > total) {
value = total;
} else if (value < 0) {
value = 0;
}
this.value = value;
remainder = total - value;
remainderDiv = remainder / otherInputs.length;
sum = value;
$.each(otherInputs, function(input) {
sum += Number(otherInputs[input].value);
});
if (sum > total) {
otherInputs.val(remainderDiv);
}
});
}
else if (option == '2' && source==0) {
var total = 20;
$("span").text(total);
$('.balance').attr({"min":0, "max":total}).on('input', function() {
var value = parseInt(this.value);
var otherInputs = $('.balance').not(this);
var remainderDiv;
var remainder, sum;
if (isNaN(value)) {
value = 0;
} else if (value > total) {
value = total;
} else if (value < 0) {
value = 0;
}
this.value = value;
remainder = total - value;
remainderDiv = remainder / otherInputs.length;
sum = value;
$.each(otherInputs, function(input) {
sum += Number(otherInputs[input].value);
});
if (sum > total) {
otherInputs.val(remainderDiv);
}
});
}
<!--html-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select onchange="changeValue(this,0)">
<option value="1">1-person</option>
<option value="2">2-10 group</option>
</select>
<input type="number" class="balance">
<input type="number" class="balance">
<!--html-->
how would you do it that the remainder doesn't go in the input field two. but it should still minus from each other though when the user puts in a value. so if max =10. when the user inputs 5 in field one and puts zero in field two that would be correct. But if he puts 5 in field one and 6 in field two that would be incorrect. how could i do that using this code.
Update: Using a dropdown to control the global MAX variable:
var MAX = 1;
function changeMax(dropdown) {
switch (dropdown.selectedIndex) {
case 0:
MAX = 1;
break;
case 1:
MAX = 10;
break;
}
}
$('.balance').on('input', function() {
var inputs = $(".balance");
var currentInput = $(this);
var otherInput = null;
for (var i = 0; i < inputs.length; i++) {
if (!$(inputs[i]).is($(this))) {
otherInput = $(inputs[i]);
}
}
var currentValue = parseInt(currentInput.val(), 10);
var otherValue = parseInt(otherInput.val(), 10);
if (isNaN(otherValue)) {
otherValue = 0;
}
// disable entering "0000.."
if (isNaN(currentValue)) {
currentValue = 0;
currentInput.val(0);
}
// disable entering negative values
if (currentValue < 0) {
currentValue = 0;
currentInput.val(0);
}
var sum = currentValue + otherValue;
if (sum > MAX) {
var offset = sum - MAX;
currentInput.val(currentValue - offset);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select onchange="changeMax(this)">
<option value="1">1-person</option>
<option value="2">2-10 group</option>
</select>
<input type="number" class="balance">
<input type="number" class="balance">
I tried to keep it as simple as it can be.
MAX is set to 10. If you enter 2 on the first input, you can enter [0,1,2,3,4,5,6,7,8] on the other input. You can also enter negative values. If you don't want to, simply uncomment the commented part.
var MAX = 10;
$('.balance').on('input', function() {
var inputs = $(".balance");
var currentInput = $(this);
var otherInput = null;
for (var i = 0; i < inputs.length; i++) {
if (!$(inputs[i]).is($(this))) {
otherInput = $(inputs[i]);
}
}
var currentValue = parseInt(currentInput.val(), 10);
var otherValue = parseInt(otherInput.val(), 10);
if (isNaN(otherValue)) {
otherValue = 0;
}
/* if (currentValue < 0) {
currentValue = 0;
currentInput.val(0);
} */
var sum = currentValue + otherValue;
if (sum > MAX) {
var offset = sum - MAX;
currentInput.val(currentValue - offset);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="balance">
<input type="number" class="balance">

How to use AJAX or JSON in this code?

I am creating a website application that allows users to select a seat, if it is not already reserved, and reserve it.
I have created a very round about way of getting the seats that are previously reserved using iFrames, however that was temporarily, now I need to make it secure and "proper javascript code" using proper practices. I have no clue what AJAX (or JSON) is, nor how to add it to this code, but it needs to get the file "seatsReserved"+this.id(that is the date)+"Que.html" and compare the string of previously reserved seats to see which class to make the element. If this is horrible, or if any of the other things could work better, I am open to criticism to everything. Thank you all!
Here is the javascript code:
A little side note, all of the if statements are due to different amount of seats in each row
<script>
var i = " 0 ";
var counter = 0;
var leng=0;
document.getElementById("Show1").addEventListener("click", changeDay);
document.getElementById("Show2").addEventListener("click", changeDay);
document.getElementById("Show3").addEventListener("click", changeDay);
function changeDay() {
var iFrame = document.getElementById("seatList");
iFrame.src = "seatsReserved" + this.id + "Que.html";
document.getElementById('date').innerHTML = this.id;
var seatsTaken = iFrame.contentWindow.document.body.innerHTML;
var k = 0;
let = 'a';
var lc = 0;
for (lc = 1; lc <= 14; lc++) {
if (lc == 1) {
leng = 28;
}
else if (lc == 2) {
leng = 29;
}
else if (lc == 3) {
leng = 32;
}
else if (lc == 4 || lc == 6 || lc == 12 || lc == 14) {
leng = 33;
}
else if (lc == 5 || lc == 13) {
leng = 34;
}
else if (lc == 8 || lc == 10) {
leng = 35;
}
else {
leng = 36;
}
for (k = 1; k <= leng; k++) {
if (seatsTaken.indexOf((" " +
let +k + " ")) <= -1) {
seat = document.getElementById(let +k);
seat.removeEventListener("click", selectedSeat);
}
else {
document.getElementById(let +k).className = "openseat";
document.getElementById(let +k).removeEventListener("click", doNothing);
}
}
let = String.fromCharCode(let.charCodeAt(0) + 1);
}
}
function loadChanges() {
var iFrame = document.getElementById("seatList");
var seatsTaken = iFrame.contentWindow.document.body.innerHTML;
var k = 0;
let = 'a';
var lc = 0;
var leng = 0;
for (lc = 1; lc <= 14; lc++) {
if (lc == 1) {
leng = 28;
}
else if (lc == 2) {
leng = 29;
}
else if (lc == 3) {
leng = 32;
}
else if (lc == 4 || lc == 6 || lc == 12 || lc == 14) {
leng = 33;
}
else if (lc == 5 || lc == 13) {
leng = 34;
}
else if (lc == 8 || lc == 10) {
leng = 35;
}
else {
leng = 36;
}
for (k = 1; k <= leng; k++) {
if (seatsTaken.indexOf((" " +
let +k + " ")) <= -1) {
seat = document.getElementById(let +k);
seat.addEventListener("click", selectedSeat);
seat.className = "openseat";
}
else {
document.getElementById(let +k).className = "notAvailible";
document.getElementById(let +k).addEventListener("click", doNothing);
}
}
let = String.fromCharCode(let.charCodeAt(0) + 1);
}
i = " 0 ";
counter = 0;
document.getElementById("seatString").innerHTML = i;
document.getElementById("getSeats").value = i;
document.getElementById("seatnums").innerHTML = counter;
}
i = document.getElementById("seatString").innerHTML;
counter = document.getElementById("seatnums").innerHTML;
function selectedSeat() {
var w = this.id;
var l = (" " + w);
var b = (" " + w + " ");
if (counter < 5) {
if (i.indexOf(b) <= 0) {
this.className = "closedseat";
i = i + b;
i = i.replace(" 0 ", " ");
document.getElementById("seatString").innerHTML = i;
document.getElementById("getSeats").value = i;
counter = counter + 1;
document.getElementById("seatnums").innerHTML = counter;
}
else if (i.indexOf(b) > 0) {
this.className = "openseat";
i = i.replace(b, "");
document.getElementById("seatString").innerHTML = i;
document.getElementById("getSeats").value = i;
counter = counter - 1;
document.getElementById("seatnums").innerHTML = counter;
}
}
else if (i.indexOf(b) > 0) {
this.className = "openseat";
i = i.replace(b, "");
document.getElementById("seatString").innerHTML = i;
document.getElementById("getSeats").value = i;
counter = counter - 1;
document.getElementById("seatnums").innerHTML = counter;
}
}
function doNothing() {
}
var rannum = Math.random() * 1000;
document.getElementById('getConfirmation').value = rannum;
</script>

JS/JSp issue in IE 10 for scrollbar and sorting

I am facing issue in table where we are using scroll bar and sorting.
In compatible mode sorting option is coming where as not coming in non compatible mode
Please suggest changes in js or jsp
function makeScrollableTable(tbl, scrollFooter, height, hasSelectAllButton, hasAddButton, columnNo) {
var c, pNode, hdr, ftr, wrapper, rect;
//alert("Shree");
if (typeof tbl == 'string') tbl = document.getElementById(tbl);
pNode = tbl.parentNode;
fixTableWidth(tbl);
c = container.length;
container[c] = document.createElement('<SPAN style="height: 100; overflow: auto;">');
container[c].id = tbl.id + "Container";
pNode.insertBefore(container[c], tbl);
container[c].appendChild(tbl);
container[c].style.width = tbl.clientWidth + 2 * tbl.clientLeft + scrollbarWidth();
hdr = tbl.cloneNode(false);
hdr.id += 'Header';
hdr.appendChild(tbl.tHead.cloneNode(true));
tbl.tHead.style.display = 'none';
if (!scrollFooter || !tbl.tFoot) {
ftr = document.createElement('<SPAN style="width:1;height:1;clip: rect(0 1 1 0);background-color:transparent;">');
ftr.id = tbl.id + 'Footer';
ftr.style.border = tbl.style.border;
ftr.style.width = getActualWidth(tbl) + 2 * tbl.clientLeft;
ftr.style.borderBottom = ftr.style.borderLeft = ftr.style.borderRight = 'none';
} else {
ftr = tbl.cloneNode(false);
ftr.id += 'Footer';
ftr.appendChild(tbl.tFoot.cloneNode(true));
ftr.style.borderTop = 'none';
tbl.tFoot.style.display = 'none';
}
wrapper = document.createElement('<table border=0 cellspacing=0 cellpadding=0>');
wrapper.id = tbl.id + 'Wrapper';
pNode.insertBefore(wrapper, container[c]);
wrapper.insertRow(0).insertCell(0).appendChild(hdr);
wrapper.insertRow(1).insertCell(0).appendChild(container[c]);
wrapper.insertRow(2).insertCell(0).appendChild(ftr);
wrapper.align = tbl.align;
tbl.align = hdr.align = ftr.align = 'left';
hdr.style.borderBottom = 'none';
tbl.style.borderTop = tbl.style.borderBottom = 'none';
// adjust page size
if (c == 0 && height == 'auto') {
onResizeAdjustTable();
onResizeHandler = window.onresize;
window.onresize = onResizeAdjustTable;
} else {
container[c].style.height = height;
}
//added by Venkatesh Bhat e-mail:vb106#dcx
//alert("");
if (hasSelectAllButton) {
//include select all button
var selButton = document.createElement('<input id="_myButton11" type="button" value="Select All" onClick="selectAll();">');
insertNode(selButton);
}
if (hasAddButton) {
var btext = '<input id="_myButton12" type="button" value="Add" onClick="posCursor(\'' + tbl.id + '\',\'' + columnNo + '\');">';
var addButton = document.createElement(btext);
insertNode(addButton);
}
}
//added by Venkatesh Bhat e-mail:vb106#dcx
function insertNode(toInsert) {
var tbs = document.getElementsByTagName('input');
for (var i = 0; i < tbs.length; i++) {
if (tbs[i].type == "button") {
var backButton = tbs[i];
var text = backButton.value.toUpperCase();
if (text == "BACK") {
var pNode = backButton.parentNode;
pNode.insertBefore(toInsert, backButton);
var textNode = document.createTextNode(" ");
pNode.insertBefore(textNode, backButton);
return;
}
}
}
}
//added by Venkatesh Bhat e-mail:vb106#dcx
function posCursor(tbl, columnNo) {
var table = document.getElementById(tbl);
var rows = table.rows;
for (var i = 0; i < rows.length; i++) {
//cells = rows[i].cells;
//if(columnNo > cells.length) continue;
var cell = rows[i].cells[columnNo];
if (getFocus(cell) == true) {
selectCheckBox(rows[i].cells[0]);
return;
}
}
}
//added by Venkatesh Bhat e-mail:vb106#dcx
function selectCheckBox(node) {
var children = node.children;
//check if this is a leaf node
if (children.length == 0) {
//if so then see if this is a checkbox input node
if (node.tagName == "INPUT" && node.type == "checkbox") {
node.checked = true;
return true;
} else {
return false;
}
} else {
//this is a parent node
for (var i = 0; i < children.length; i++) {
if (selectCheckBox(children[i]) == true) return true;
}
}
return false;
}
//added by Venkatesh Bhat e-mail:vb106#dcx
function getFocus(node) {
var children = node.children;
//check if this is a leaf node
if (children.length == 0) {
//if so then see if this is a text input node
if (node.tagName == "INPUT" && node.type == "text" && node.value == "") {
node.focus();
return true;
} else {
return false;
}
} else {
//this is a parent node
for (var i = 0; i < children.length; i++) {
if (getFocus(children[i]) == true) return true;
}
}
return false;
}
//added by Venkatesh Bhat e-mail:vb106#dcx
function selectAll() {
//added by Venkatesh Bhat e-mail:vb106#dcx
var button = document.getElementById('_myButton11');
var butText = button.value;
var tbs = document.getElementsByTagName('input');
if (butText == 'Deselect All') {
button.value = "Select All";
for (var i = 0; i < tbs.length; i++) {
if (tbs[i].type == "checkbox") {
tbs[i].checked = false;
}
}
} else {
button.value = "Deselect All";
for (var i = 0; i < tbs.length; i++) {
if (tbs[i].type == "checkbox") {
tbs[i].checked = true;
}
}
}
}
function onResizeAdjustTable() {
if (onResizeHandler) onResizeHandler();
var rect = container[0].getClientRects()(0);
var h = document.body.clientHeight - (rect.top + (document.body.scrollHeight - rect.bottom));
container[0].style.height = (h > 0) ? h : 1;
}
function printPage() {
var tbs = document.getElementsByTagName('TABLE');
var e;
for (var i = 0; i < container.length; i++) container[i].style.overflow = '';
window.print();
for (var i = 0; i < container.length; i++) container[i].style.overflow = 'auto';
}

JavaScript Using a Loaded Array to Pull data from And display in Text box

I have some code here that will already have data in an array (called setArray). And will loop through that data depending on the length of the transArray and put the random data into the text box fields. Here is the full code: http://jsfiddle.net/EABRJ/
var loadBills = function ()
{
clearFields();
mySetArray(); //Fills the transArray randomly with 1-4 items
// TEMPORARY ALERT BELOW SO YOU CAN SEE THAT THE ARRAY IS BEING LOADED
// alert(transArray);
for ( var i = 0; i <= transArray.length; i++)
{
var items = 'item' + i;
var amounts = 'amount' + i;
splittedData = transArray[i].split(":");
items.value += splittedData[0];
amounts.value += splittedData[1];
}
}
var clearFields = function ()
{
for ( i = 1; i <= 4; i++)
{
itemName = 'item' + i;
$(itemName).value = "";
}
for ( i = 1; i <= 4; i++)
{
amountName = 'amount' + i;
$(amountName).value = "";
}
$('total').value = "";
}
var mySetArray = function ()
{
var myRandom = Math.floor((Math.random() * 100) / 25) + 1; //a number between 1 and 4
transArray = new Array(); //Resets the Array to empty
if (myRandom == 1)
{
transArray[0] = "Food:200";
}
if (myRandom == 2)
{
transArray[0] = "Food:200";
transArray[1] = "Toys:700";
}
if (myRandom == 3)
{
transArray[0] = "Food:200";
transArray[1] = "Toys:700";
transArray[2] = "Mortgage:1800";
}
if (myRandom == 4)
{
transArray[0] = "Food:200";
transArray[1] = "Toys:700";
transArray[2] = "Mortgage:1800";
transArray[3] = "Cable:130";
}
}
window.onload = function ()
{
$("loadbills").onclick = loadBills;
$("clearfields").onclick = clearFields;
}
Here's corrected JS code..
DEMO FIDDLE
var loadBills = function () {
clearFields();
mySetArray(); //Fills the transArray randomly with 1-4 items
// TEMPORARY ALERT BELOW SO YOU CAN SEE THAT THE ARRAY IS BEING LOADED
console.log(transArray);
for (var i = 0; i <= transArray.length; i++) {
if(transArray[i] != 'undefined' && transArray[i] != null) {
var sdata = transArray[i].split(":");
$("#item"+(i+1)).val(sdata[0]);
$("#amount"+(i+1)).val(sdata[1]);
}
}
}
var clearFields = function () {
for (i = 1; i <= 4; i++) {
$("#item"+i).val("");
}
for (i = 1; i <= 4; i++) {
$("#amount"+i).val("");
}
$('total').value = "";
}
var mySetArray = function () {
var myRandom = Math.floor((Math.random() * 100) / 25) + 1; //a number between 1 and 4
transArray = new Array(); //Resets the Array to empty
if (myRandom == 1) {
transArray[0] = "Food:200";
}
if (myRandom == 2) {
transArray[0] = "Food:200";
transArray[1] = "Toys:700";
}
if (myRandom == 3) {
transArray[0] = "Food:200";
transArray[1] = "Toys:700";
transArray[2] = "Mortgage:1800";
}
if (myRandom == 4) {
transArray[0] = "Food:200";
transArray[1] = "Toys:700";
transArray[2] = "Mortgage:1800";
transArray[3] = "Cable:130";
}
}
$("#loadbills").on("click", loadBills);
$("#clearfields").on("click", clearFields);

Categories

Resources