For some reason i can't get the variable 'total' to define at all...
I defined it on like 74 but it does't want to stick for some reason.. what am i doing wrong? Thanks in advance!
$(document).ready(function() {
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
$(".tab-content").hide(); //Hide all content
$("ul.tabs li:first").addClass("active").show(); //Activate first tab
$(".tab-content:first").show(); //Show first tab content
$('.question-form-submit').click(function(e) {
e.preventDefault();
var activeTab = '#'+$(this).attr('name');
var activeClass = activeTab.substr(5);
$("ul.tabs li").removeClass("active");
$('ul li:nth-child('+activeClass+')').addClass("active"); //Add "active" class to selected tab
$(".tab-content").hide(); //Hide all tab content
$(activeTab).fadeIn(); //Fade in the active ID content
$('.meter-value').removeClass('meter-width');
switch (activeClass) {
case '2' :
$('.meter-value').attr('style', 'background-color: #9496c9; width: 46.5%;');
break;
case '3' :
$('.meter-value').attr('style', 'background-color: #9496c9; width: 67%;');
break;
case '4' :
$('.meter-value').attr('style', 'background-color: #9496c9; width: 100%;');
break;
}
return false;
});
$('.quantity, .init_cost').change(function() {
var row_id = $(this).attr('id');
var row_number = row_id.substr(9);
var item_cost = $('#cost_'+row_number).attr('value');
var item_quantity = $('#quantity_'+row_number).attr('value');
var final_cost = item_cost * item_quantity;
$('#final_cost_'+row_number).val(final_cost).formatCurrency();;
});
$('.row input').each(function(index) {
var row_id = $(this).attr('id');
var row_number = row_id.substr(9);
var item_cost = $('#cost_'+row_number).attr('value');
var item_quantity = $('#quantity_'+row_number).attr('value');
var final_cost = item_cost * item_quantity;
$('#final_cost_'+row_number).val(final_cost).formatCurrency();;
});
var total = 0;
$('.final_cost').each(function(index) {
var final_cost = $(this).attr('value').substr(1);
var total = total + final_cost;
console.log(total);
})
});
The inner declaration on the line var total = total + final_cost; hides the outer declaration from the line var total = 0;.
The total in the each function is shadowing the outer one.
A simpler example of the same thing is here:
(function()
{
var total = 1;
console.log("total 1: " + total);
(function()
{
console.log("total 2: " + total);
var total = total + 3;
console.log("total 3: " + total);
})()
})();
In addition to the shadowing, you have to consider hoisting. Because the inner var is hoisted to the top, the inner function is roughly equivalent to:
function()
{
var total = undefined;
console.log("total 2: " + total);
total = total + 3;
console.log("total 3: " + total);
}
In this case, I think you simply don't want the inner var keyword. In other cases, you would use a different variable name.
You're redefining total every time you loop through
$('.final_cost').each(function(index) {
var final_cost = $(this).attr('value').substr(1);
var total = total + final_cost;
console.log(total);
})
Why not try this?
$('.final_cost').each(function(index) {
var final_cost = $(this).attr('value').substr(1);
total = total + final_cost;
console.log(total);
})
Try to remove second var before the total.
total = total + final_cost;
That's because you declare the variable two times (everytime you write var total it's declared anew. So you have one outside of the "final_cost" function and one inside, which is set to total from outside + final_cost. So in effect you always log the value of final_cost.
Just write total = total + final_cost; and it should work.
Syntax error, killing your script:
$('#final_cost_'+row_number).val(final_cost).formatCurrency();;
^--- extra ;
Next time, check your browser's console (shift-ctrl-J in FF/Chrome) for errors. Things like this are reported instantly.
I'd replace the line:
var total = total + final_cost;
with:
total += final_cost
Not sure about this answer but, try defining the variable total first with a default value like 0 and then use the total + final_cost operation.
var total = 0;
total += final_cost;
why is that? when you declare the total without a default value, the value will be "undefined" so the javascript will represent the following as :
var total = "undefined" + final_cost;
I guess that's the error.
Related
I setup a simple checkout with increment/subtract buttons (function calculates total price -> price * quantity) and now struggling getting the variable with the total amount out of that function. As a result I need the total amount (in the functions it's total1 or total2) in the global variable total. In my example it doesn't work, because calling the function incr() or subt() for the variable total triggers the function and adds or increment the value of the value again. This is what I have so far:
<script>
var quantity = document.getElementById("qty").value;
var counter = document.getElementById("qty").value;
// subtract function triggered by subtract button
function subt(){
var quantity = document.getElementById("qty").value = --counter;
document.getElementById('total').innerHTML = 'Total ' + quantity * 298 + ".-";
var total1 = document.getElementById('current').innerHTML = quantity * 298;
return total1;
}
// increment function triggered by increment button
function incr(){
var quantity = document.getElementById("qty").value = ++counter;
document.getElementById('total').innerHTML = 'Total ' + quantity * 298 + ".-";
var total2 = document.getElementById('total').innerHTML = quantity * 298;
return total2;
}
var total = incr();
</script>
This is what my code looks now:
var counter = 1;
var quantity = document.getElementById("qty").value;
var initial = document.getElementById('total').innerHTML = 'Total ' + quantity * 298 + ".-";
var add = document.getElementById("add");
var sub = document.getElementById("sub");
add.addEventListener("click", function(e) {
calcFunc(1);
});
sub.addEventListener("click", function(e) {
calcFunc(-1);
});
function calcFunc(operation) {
quantity = operation < 0 ? --counter : ++counter;
document.getElementById('total').innerHTML = 'Total ' + quantity * 298 + ".-";
var total = document.getElementById('current').innerHTML = quantity * 298;
return total;
}
I think #epascarello means to create one function that get's a parameter passed to it [-1 or 1] in this case depending on if the add or subtract button is pressed.
I've been taught that you should avoid solutions using parameterless functions with no options it creates long drawn out code.
Example below:
var total = null;
addFoo.addEventListener("click", function(e) {
total = calcFunc(1);
});
minusFoo.addEventListener("click", function(e) {
total = calcFunc(-1);
});
function calcFunc(operation) {
quantity = operation < 0 ? --counter : ++counter;
document.getElementById('total').innerHTML = 'Total ' + quantity * 298 + ".-";
var total = document.getElementById('current').innerHTML = quantity * 298;
return total;
}
I'm not quite sure what this is going to do though... :(
Is this what you had in mind #epascarello?
I have a form with few fields which does a small calculation. Once all the dropdowns are populated and clicked on Add Button It will display time for specific task. Likewise If you do the calculation couple of times the data will display in the table. and all values in time column will sum add together and display in another row. I have already implemented that. But it keeps adding to the existing value each time.
Refer to the image:
JS Fiddle
$(document).ready(function () {
$('#calculate').click(function () {
let tr = $("<tr/>").appendTo("#data tbody");
$('#calc input, #calc select').each( function (index) {
var input = $(this);
$(tr).append('<td class=row-'+ $(input).attr("id") + '>' + $(input).val() + '</td>');
});
const componentFactor = $(tr).children(".row-component").text();
const units = $(tr).children(".row-units").text();
const total = componentFactor*units;
$(tr).append('<td>' + total + '</td>');
$("#calc")[0].reset();
$("#total").html(sumColumn(5));
function sumColumn(index) {
var total = 0;
$("td:nth-child(" + index + ")").each(function() {
total += parseInt($(this).text(), 10) || 0;
});
return total;
}
});
});
The problem is that you are including the total line in your sum function. The .each correctly hits every TD element at the right index, but it is also including the first line.
If you modify your sum function like so, it works.
function sumColumn(index) {
var total = 0;
$("td:nth-child(" + index + ")").each(function() {
if(this.id !== 'total') {
total += parseInt($(this).text(), 10) || 0;
}
});
return total;
}
Same conclusion, you are adding total in your code; you can also use the following option:
function sumColumn(index) {
var total = 0;
$("tr> td:nth-child(" + index + ")").not(':first').each(function(i,item) {
total += parseInt($(this).text(), 10) || 0;
});
return total;
}
You can see it working here: JSFiddle demo
I'm trying to replace the <li> with 1. 2. 3. respectively. I managed to change the <li> to a number, but that number is 0. The loop doesn't want to work. To be honest, this method may be impossible.
Take a look at the Fiddle if you'd like.
This is my function(){...} :
function doIt(){
var input = document.getElementById("input");
var li = /<li>/; // match opening li
var liB = /<\/li>/; // match closing li
var numberOfItems = input.value.match(li).length; // number of lis that occur
for(var i = 0; i < numberOfItems; i++) {
insertNumber(i); // execute insertNumber function w/ parameter of incremented i
}
function insertNumber(number){
input.value = input.value.replace(li, number + "." + " ").replace(liB, "");
}
}
I understand the insertNumber(){...} function is not necessary.
Here's an alternative method, turning your HTML textarea contents into DOM elements that jQuery can manipulate and managing them that way:
function doIt() {
var $domElements = $.parseHTML( $('#input').val().trim() ),
output = [],
i = 1;
$.each($domElements, function(index, element) {
if($(this).text().trim() != '') {
output.push( i + '. ' + $(this).text().trim() );
i++;
}
});
$('#input').val(output.join('\n'));
}
I am using javascript to fill some contents in my form,but when i use a variable to get the object,there post a error "TypeError: mytitle is null"
Here is my code:
var num=0;
function add(){
var tr1=document.getElementById('itable').insertRow(1);
var c0=tr1.insertCell(0);
var c1=tr1.insertCell(1);
var c2=tr1.insertCell(2);
var c3=tr1.insertCell(3);
var c4=tr1.insertCell(4);
c0.innerHTML="<input type='checkbox' name='ck'/>";
c1.innerHTML="<input type='text' style='width:150px;'id='news_title"+ num + "' name='news_title"+num+ "' value="+ document.getElementById('news_title').value+"></input>";
c1.className="titlelimit";
$(".titlelimit").wordLimit(10);
c2.innerHTML="<input type='text' style='width:200px;' id='news_content"+num+"' name='news_content"+num+"' value="+ document.getElementById('news_content').value+"></input>";
c2.className="detailindex";
$(".detailindex").wordLimit(50);
c3.innerHTML="<input type='text' readonly='readonly 'maxlength='4' style='width:70px;' id='news_type"+num+"' name='news_type"+num+"' value="+ document.getElementById('news_type').value+"></input>";
c4.innerHTML="<input type='button' value='删除' onclick='del(this)' />";
num=num+1;
$("#news_title").attr("value","");
$("#news_content").attr("value","");
$("#news_type").attr("value","");
}
window.onload = loadtable;
function loadtable() {
var newstitle = myform.mynewstitle.value
alert(newstitle)
var titlearray = newstitle.split(",");
for(i = 0;i<titlearray.length;i++){
alert(titlearray[i]);
add();
var mytitle = document.getElementById('news_title'+num);
mytitle.value = titlearray[i];
num = num +1;
}
}
num has a global scope, so at the end of add() its value it's 1
when you are in the for cycle, you are using incorrectly num to create your id name.
You have to use i.
var mytitle = document.getElementById('news_title'+i);
and this instruction it's usless, remove it last one of cicle for:
num = num +1;
so:
function loadtable() {
var newstitle = myform.mynewstitle.value
alert(newstitle)
var titlearray = newstitle.split(",");
for(i = 0;i<titlearray.length;i++){
alert(titlearray[i]);
add();
var mytitle = document.getElementById('news_title'+i);
mytitle.value = titlearray[i];
}
You are creating an element with num - 'news_title"+ num
You then increment that with num=num+1;
You then try and find an element with 'news_title'+num
If you created an element 'news_title0', by the time your look for it you're looking for an element with id 'news_title1'
Remove the num=num+1; from your add function, since it already correctly exists in the loop in the loadtable function.
The error is in the following line,
var mytitle = document.getElementById('news_title'+num);
mytitle is not finding any element, you might want to check what 'news_title'+num returns.
I have a table with n number of rows with checkboxes and a what i want to do is if i select a checkbox the value should go to the text area, so i stored all elements in an array first, but it isnt happening, as you can see i added alerts as well to check it out. please help.
window.onload = function () {
var oRows = document.getElementById('rnatable').getElementsByTagName('tr');
var iRowCount = oRows.length;
alert('Your table has ' + iRowCount + ' rows.');
var i = 0;
cb = new Array(iRowCount);
while (i <= iRowCount) {
var id = 'check'+ i;
cb[i] = document.getElementById(id);
i++;
}
//alert('Your table has ' + cb[i].value + ' rows.');
for(var a=0; a < iRowCount; a++) {
var fasta = document.getElementById('fasta');
if(cb[a].checked) {
fasta.value = cb.value + ",";
};
};
}
Are you seeing an error in the console? I suspect that when while (i <= iRowCount) runs when i === iRowCount that document.getElementById(id) isn't yielding a result, and that then when you use that value, bad things happen.
Also, each lap through the fasta loop overwrites the previous value. You probably want something like fasta.value += cb.value + ","; instead.