javascript function for calculating - javascript

I meet a trouble with a function. actually I need to make this function to perform a calculation on some text fields. When I worked on a single line no problems. But recently, someone asked to make a table with multiple lines (one line can be added dynamically) so, I do the following function so that it can not only duplicate line but id change all the fields concerned, so I add class to these fields. therefore I proceed as follows:
function clone(line) {
newLine = line.cloneNode(true);
line.parentNode.appendChild(newLine);
var tab = document.getElementsByClassName('libelle_debours')
var i = -1;
while (tab[++i]) {
tab[i].setAttribute("id", "_" + i);
};
var cab = document.getElementsByClassName('ht_no_tva')
var j = -1;
while (cab[++j]) {
cab[j].setAttribute("id", "_" + j);
};
var dab = document.getElementsByClassName('ht_tva')
var k = -1;
while (dab[++k]) {
dab[k].setAttribute("id", "_" + k);
};
var eab = document.getElementsByClassName('taux')
var l = -1;
while (eab[++l]) {
eab[l].setAttribute("id", "_" + l);
};
var fab = document.getElementsByClassName('tva')
var m = -1;
while (fab[++m]) {
fab[m].setAttribute("id", "_" + m);
};
}
function delRow() {
var current = window.event.srcElement;
//here we will delete the line
while ((current = current.parentElement) && current.tagName != "TR");
current.parentElement.removeChild(current);
}
The problem in fact is the second function that is used to make the calculation:
function calcdebours() {
var taux = document.getElementById('debours_taux_tva').value;
var ht_no_tva = document.getElementById('debours_montant_ht_no_tva').value;
var ht_tva = document.getElementById('debours_montant_ht_tva').value;
var tva = Math.round((((ht_tva) * (taux)) / 100) * 100) / 100;;
if (taux == '') {
taux = 0;
}
if (ht_no_tva == '') {
ht_no_tva = 0;
}
if (ht_tva == '') {
ht_tva = 0;
}
document.getElementById('debours_montant_tva').value = tva;
document.getElementById('debours_montant_ttc').value = (tva) + parseFloat(ht_tva) + parseFloat(ht_no_tva)
}
function
montant_debours() {
var ttc = document.getElementById('debours_montant_ttc').value;
var ttc2 = document.getElementById('debours_montant_ttc2').value;
if (ttc == '') {
var ttc = 0;
} else {
var ttc = document.getElementById('debours_montant_ttc').value;
}
if (ttc2 == '') {
var ttc2 = 0;
} else {
var ttc2 = document.getElementById('debours_montant_ttc2').value;
}
tx = parseFloat(ttc) + parseFloat(ttc2);
document.getElementById('ttc_cheque').value = Math.round(tx * 100) / 100;
}
As Id are not the same, do I have to create as many functions
there are lines?
Is it possible to fit a single function to process each line?
If so can you tell me how?

If I'm not mistaken you can use for loop and append increment to the end of element's id. Like this:
trs = document.getElementById('container Id').getElementsByTagName('tr');
For (var i = 1, i <= trs.length; i++)
{
var el = document.getElementById('debours_montant_ttc' + i);
}

Related

Blogger random post display to prevent no posts infinite loop

How can I get Blogger to display random posts, while preventing an infinite loop when there are no posts to display?
Here is my JavaScript code which I am attempting to use:
<script>
var dt_numposts = 10;
var dt_snippet_length = 100;
var dt_info = 'true';
var dt_comment = 'Comment';
var dt_disable = '';
var dt_current = [];
var dt_total_posts = 0;
var dt_current = new Array(dt_numposts);
function totalposts(json) {
dt_total_posts = json.feed.openSearch$totalResults.$t
}
document.write('<script type=\"text/javascript\" src=\"/feeds/posts/summary?max-results=100&orderby=published&alt=json-in-script&callback=totalposts\"><\/script>');
function getvalue() {
for (var i = 0; i < dt_numposts; i++) {
var found = false;
var rndValue = get_random();
for (var j = 0; j < dt_current.length; j++) {
if (dt_current[j] == rndValue) {
found = true;
break
}
};
if (found) {
i--
} else {
dt_current[i] = rndValue
}
}
};
function get_random() {
var ranNum = 1 + Math.round(Math.random() * (dt_total_posts - 1));
return ranNum
};
function random_list(json) {
a = location.href;
y = a.indexOf('?m=0');
for (var i = 0; i < dt_numposts; i++) {
var entry = json.feed.entry[i];
var dt_posttitle = entry.title.$t;
if ('content' in entry) {
var dt_get_snippet = entry.content.$t
} else {
if ('summary' in entry) {
var dt_get_snippet = entry.summary.$t
} else {
var dt_get_snippet = "";
}
};
dt_get_snippet = dt_get_snippet.replace(/<[^>]*>/g, "");
if (dt_get_snippet.length < dt_snippet_length) {
var dt_snippet = dt_get_snippet
} else {
dt_get_snippet = dt_get_snippet.substring(0, dt_snippet_length);
var space = dt_get_snippet.lastIndexOf(" ");
dt_snippet = dt_get_snippet.substring(0, space) + "…";
};
for (var j = 0; j < entry.link.length; j++) {
if ('thr$total' in entry) {
var dt_commentsNum = entry.thr$total.$t + ' ' + dt_comment
} else {
dt_commentsNum = dt_disable
};
if (entry.link[j].rel == 'alternate') {
var dt_posturl = entry.link[j].href;
if (y != -1) {
dt_posturl = dt_posturl + '?m=0'
}
var dt_postdate = entry.published.$t;
if ('media$thumbnail' in entry) {
var dt_thumb = entry.media$thumbnail.url
} else {
dt_thumb = "https://blogspot.com/"
}
}
};
document.write('<img alt="' + dt_posttitle + '" src="' + dt_thumb + '"/>');
document.write('<div>' + dt_posttitle + '</div>');
if (dt_info == 'true') {
document.write('<span>' + dt_postdate.substring(8, 10) + '/' + dt_postdate.substring(5, 7) + '/' + dt_postdate.substring(0, 4) + ' - ' + dt_commentsNum) + '</span>'
}
document.write('<div style="clear:both"></div>')
}
};
getvalue();
for (var i = 0; i < dt_numposts; i++) {
document.write('<script type=\"text/javascript\" src=\"/feeds/posts/summary?alt=json-in-script&start-index=' + dt_current[i] + '&max-results=1&callback=random_list\"><\/script>')
};
</script>
Expected output:
?
Actual output:
?
It looks like your post is mostly code; please add some more details.
It looks like you're trying to populate dt_current with dt_numposts = 10 elements. I modified getvalue() as follows, so that dt_numposts is capped at dt_total_posts, which may be 0. This allows the outer for loop to exit.
function getvalue() {
dt_numposts = (dt_total_posts < dt_numposts) ? dt_total_posts : dt_numposts;
// ...
I couldn't test this, because I don't have an example /feeds/posts/summary?max-results=100&orderby=published&alt=json-in-script&callback=totalposts JSON resource, but it works for zero posts. Whether is works for dt_numposts > 0, you'll need to test!

Getting javascript undefined TypeError

Please help....Tried executing the below mentioned function but web console always shows
TypeError: xml.location.forecast[j] is undefined
I was able to print the values in alert but the code is not giving output to the browser because of this error. Tried initializing j in different locations and used different increment methods.How can i get pass this TypeError
Meteogram.prototype.parseYrData = function () {
var meteogram = this,xml = this.xml,pointStart;
if (!xml) {
return this.error();
}
var j;
$.each(xml.location.forecast, function (i,forecast) {
j= Number(i)+1;
var oldto = xml.location.forecast[j]["#attributes"].iso8601;
var mettemp=parseInt(xml.location.forecast[i]["#attributes"].temperature, 10);
var from = xml.location.forecast[i]["#attributes"].iso8601;
var to = xml.location.forecast[j]["#attributes"].iso8601;
from = from.replace(/-/g, '/').replace('T', ' ');
from = Date.parse(from);
to = to.replace(/-/g, '/').replace('T', ' ');
to = Date.parse(to);
if (to > pointStart + 4 * 24 * 36e5) {
return;
}
if (i === 0) {
meteogram.resolution = to - from;
}
meteogram.temperatures.push({
x: from,
y: mettemp,
to: to,
index: i
});
if (i === 0) {
pointStart = (from + to) / 2;
}
});
this.smoothLine(this.temperatures);
this.createChart();
};
You are trying to access the element after the last one. You can check if there is the element pointed by j before proceeding:
Meteogram.prototype.parseYrData = function () {
var meteogram = this,
xml = this.xml,
pointStart;
if (!xml) {
return this.error();
}
var i = 0;
var j;
$.each(xml.location.forecast, function (i, forecast) {
j = Number(i) + 1;
if (!xml.location.forecast[j]) return;
var from = xml.location.forecast[i]["#attributes"].iso8601;
var to = xml.location.forecast[j]["#attributes"].iso8601;
});
};

Multiplying variables and showing result in a box

I'm having a problem when trying to multiply the totalPallets by the price-per-pallet ($25) and then showing that in the productSubTotal box. With the code as it is right now, the quatity total shows but when I try to get the price result, it doesn't show the operation. Also, if I try changing anythung from the code, the whole thing breaks down. I'll be thankful if anyone could help me. Thanks
// UTILITY FUNCTIONS
function IsNumeric(n) {
return !isNaN(n);
}
function calcTotalPallets() {
var totalPallets = 0;
$(".num-pallets-input").each(function() {
var thisValue = parseInt($(this).val());
if ( (IsNumeric(thisValue)) && (thisValue != '') ) {
totalPallets += parseInt(thisValue);
};
});
$("#quantitytotal").val(totalPallets);
}
function calcProdSubTotal() {
var prodSubTotal = 0;
$(".totalprice").each(function() {
var valString = parseInt(totalPallets) * multiplier;
prodSubTotal += parseInt(valString);
});
$("#product-subtotal").val(CommaFormatted(prodSubTotal));
};
// "The Math" is performed pretty much whenever anything happens in the quanity inputs
$('.num-pallets-input').bind("focus blur change keyup", function(){
// Caching the selector for efficiency
var $el = $(this);
// Grab the new quantity the user entered
var numPallets = CleanNumber($el.val());
var totalPallets = CleanNumber($el.val());
var prodSubTotal = CleanNumber($el.val());
// Find the pricing
var multiplier = $el
.parent().parent()
.find("td.price-per-pallet span")
.text();
};
// Calcuate the overal totals
calcProdSubTotal();
calcTotalPallets();
});
function CommaFormatted(amount) {
var delimiter = ",";
var i = parseInt(amount);
if(isNaN(i)) { return ''; }
i = Math.abs(i);
var minus = '';
if (i < 0) { minus = '-'; }
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);
amount = "$" + minus + n;
return amount;
}
});

How to display a div with random ID without repeating it using jQuery?

I have a function to select a random number from 0 to 45 and then I show the div with the specific ID. It's working fine but it repeats a number.
Can anyone advise so it won't repeat numbers?
I call the function onclick like this
$(".skip").click(function () {
scared++;
$("#counter").html("My current count is: " + dared);
var d = 50;
/*$(".question").addClass("hideMe");
$(this).parents("div").next("div").removeClass("hideMe");*/
var r = Math.round(Math.random() * 44) + 1;
var newquestion = "q" + r;
$('.active').removeClass("active");
$("#" + newquestion).addClass("active");
if (scared > 44) {
$('.main').fadeOut('fast');
$('.logo').switchClass("logo", "share");
$('.progress').css("display", "none");
$('.share-game').css("display", "block");
$('.hero').css("right", "-240px");
$('#score-total').html(score + '');
} else {
}
$('.red-line').append('<div id="children' + (d++) + '" class="red"></div>');
return false;
});
You can see what i did.
var usedNumbers = [];
var randomNumbers = [];
$(function() {
//Getting 20 random numbers
for (i = 0; i < 20; i++) {
randomNumbers.push(getRandomNumber());
}
console.log(randomNumbers);
function getRandomNumber() {
var hasInArray = true;
do {
var r = Math.round(Math.random() * 44) + 1;
if (usedNumbers.indexOf(r) === -1) {
usedNumbers.push(r);
hasInArray = false;
return r;
}
} while (hasInArray === true);
}
});
Warning to not set the numbers of randomnumbers more then what you want to get, because that will cause an infinite loop!
Use an array to capture the used numbers and then check that array on each click, generating a new number if that one is found. It resets back to an empty array when it is full.
var savedNumbers = [];
function getRandom() {
if (savedNumbers.length === 45) {
savedNumbers = [];
}
var r = Math.round(Math.random() * 44) + 1;
if (savedNumbers.indexOf(r) > -1) {
getRandom();
} else {
savedNumbers.push(r);
return r;
}
}
DEMO

avoid sorting in the JSP pages

var sortitems = 1;
function move(fbox, tbox, all)
{
for ( var i = 0; i < fbox.options.length; i++)
{
if (!all && fbox.options[i].selected && fbox.options[i].value != "")
{
var no = new Option();
no.value = fbox.options[i].value;
no.text = fbox.options[i].text;
tbox.options[tbox.options.length] = no;
fbox.options[i].value = "";
fbox.options[i].text = "";
}
else
{
if (all && fbox.options[i].value != "")
{
var no = new Option();
no.value = fbox.options[i].value;
no.text = fbox.options[i].text;
tbox.options[tbox.options.length] = no;
fbox.options[i].value = "";
fbox.options[i].text = "";
}
}
}
BumpUp(fbox);
if (sortitems)
SortD(tbox);
checkSelectAll();
}
This move function is getting called after clicking on the button, then it will call the sort method where sorting is happening by alphabetically. So we dont need to sort we need to populate the data as it is from the left side box to right side box and vice versa, but sorting is happening. Please help out be here.
function SortD(box)
{
var temp_opts = new Array();
var temp = new Object();
for ( var i = 0; i < box.options.length; i++)
{
temp_opts[i] = box.options[i];
}
for ( var x = 0; x < temp_opts.length - 1; x++)
{
for ( var y = (x + 1); y < temp_opts.length; y++)
{
if (temp_opts[x].value > temp_opts[y].value)
{
temp = temp_opts[x].text;
temp_opts[x].text = temp_opts[y].text;
temp_opts[y].text = temp;
temp = temp_opts[x].value;
temp_opts[x].value = temp_opts[y].value;
temp_opts[y].value = temp;
}
}
}
for ( var i = 0; i < box.options.length; i++)
{
box.options[i].value = temp_opts[i].value;
box.options[i].text = temp_opts[i].text;
}
}
Depends on the bumpup box function. The elements are moving from one box to another. It will replace the element with empty space and move to top and do for all the elements. Please help out me here
Thanks in advance
function BumpUp(box)
{
for ( var i = 0; i < box.options.length; i++)
{
if (box.options[i].value == "")
{
for ( var j = i; j < box.options.length - 1; j++)
{
box.options[j].value = box.options[j + 1].value;
box.options[j].text = box.options[j + 1].text;
}
var ln = i;
break;
}
}
if (ln < box.options.length)
{
box.options.length -= 1;
BumpUp(box);
}
}
Maybe it's just me, but it's hard to see what the issue is here.
If it is simply that SortD(tbox) is being called within the move() function, that's because
sortitems is set to 1 right at the top of the code. The value of sortitems is never changed anywhere else, so this conditional is always true and SortD is always called.
if (sortitems)
SortD(tbox);

Categories

Resources