how to remove NaN from field value and show value? - javascript

I make a dynamic form, if i delete a row then in loop result is NaN of the deleted element i want when i delete element its 0 value pass not NaN. Like i delete 5th element when 1=5 it shows NaN. How to remove this error and instead 0 will be add in sum value, how i do?
$("body").on('change', '.quantity', function() {
var that = $(this);
if ($('#itemcounter').val()==""){
$('#itemscounter').val("1");
var counter=$('#itemscounter').val();
var quantity=$('#quantity').val();
var unitprice=$('#unitprice').val();
var linetotal=quantity*unitprice;
that.parent().find('.linetotal').val(linetotal)
$("#invoicetotalamount").val(+linetotal)
var discount=document.getElementById('discount').value ;
var discountamount= discount/100 * linetotal;
var amount=linetotal-discountamount;
$("#balanceamount").val(+amount);
} else {
var counter=$('#itemscounter').val();
var quantity=$('#quantity').val();
var unitprice=$('#unitprice').val();
var linetotal=quantity*unitprice;
$('#linetotal').val(+linetotal);
var sum=linetotal;
for (i = 2; i <=counter; i++) {
var quantity=parseFloat($('#quantity' + i).val());
var unitprice=parseFloat($('#unitprice' + i).val());
var linetotal=quantity*unitprice;
$('#linetotal' + i).val(+linetotal);
alert(sum);
sum=+sum +(+(linetotal));
}
$("#invoicetotalamount").val(+sum);
var discount=document.getElementById('discount').value ;
var discountamount= discount/100 * sum;
var amount=sum-discountamount;
$("#balanceamount").val(+amount);
}
});

Check the value if its a number like this:
var quantity=parseFloat($('#quantity' + i).val());
if(isNaN(quantity)){
quantity=0;
}

you can check it with if else loop for dynamic data:
var str_val = $('#itemscounter').val();
if(str_val == NaN){
str_val =0; //use str_val at the place you want
alert(str_val);
}

You can check to see if it's NaN
var quantity = !isNaN($('#quantity' + i).val()) ? parseFloat($('#quantity' + i).val(), 2) : 0;

Related

Javascript- Dynamic variable loop

I'm trying to reduce the amount of code I repeat.
Currently I have the below:
var item1H = $(".item-1").height();
var item1W = $(".item-1").height();
$(".item-1 .text").css('margin-left', -item1W/2);
$(".item-1 .text").css('margin-bottom', -item1H/2);
var item2H = $(".item-2").height();
var item2W = $(".item-2").height();
$(".item-2 .text").css('margin-left', -item2W/2);
$(".item-2 .text").css('margin-bottom', -item2H/2);
I'm looking to put this into a for loop where the variable number would count up to whatever number I needed it to stop.
You can make function like this and use whenever you want
toSetMargin(".item-2")
toSetMargin(".item-2")
function toSetMargin(objStr){
var widthTmp = $(objStr + ' .text').height();
var heightTmp = $(objStr + ' .text').height();
obj.css('margin-left', -widthTmp/2);
obj.css('margin-bottom', -heightTmp/2)
}
This code not impact any other code.
You could use $('[class^="item-"]') to get all the elements that have a class that starts with item-, and the loop over them
$('[class^="item-"]').each(function(){
var $elem = $(this);
var item1H = $elem.height();
var item1W = $elem.width();
$elem.find('.text').css({'margin-left': -item1W/2,'margin-bottom':-item1H/2});
});
Ooh boy, one of these problems. This should help (untested):
for(i=1;i<=STOPPING_NUMBER;i++){
window["item"+i+"H"] = $(".item-"+i).height();
window["item"+i+"W"] = $(".item-"+i).width(); //Was height, accident?
$(".item-"+i+" .text").css('margin-left', 0-window["item"+i+"W"]/2); //Hope this works lol
$(".item-"+i+" .text").css('margin-bottom', 0-window["item"+i+"H"]/2);
}
Guessing these lines:
var item1W = $(".item-1").height();
var item2W = $(".item-2").height();
Should have been:
var item1W = $(".item-1").width();
var item2W = $(".item-2").width();
You could do something like:
function setCSS(item,attr,val) {
$(item +" .text").css(attr, (val * -1)/2);
}
var i, max = 10;
for(i=1;i<=max;i++) {
setCSS(".item-"+ i,"margin-left",$(".item-"+ i).width());
setCSS(".item-"+ i,"margin-bottom",$(".item-"+ i).height());
}
Or something less flexible within the function:
function setCSS(item,w,h) {
$(item +" .text").css("margin-left", (w * -1)/2);
$(item +" .text").css("margin-bottom", (h * -1)/2);
}
var i, max = 10;
for(i=1;i<=max;i++) {
setCSS(".item-"+ i,$(".item-"+ i).width()),$(".item-"+ i).height());
}
Something like this should be pretty acceptible in your case, I guess:
for (var i = 1, len = someN; i < len; i++) {
var $item = $('.item-' + i);
$item.find('.text').css({
'margin-left': -$item.width() / 2,
'margin-bottom': -$item.height() / 2
});
}

Array not resetting when input changed

I'm trying to populate select box using value from input text. So far I've been doing good in populating the select box. But the problems came when I change the input field into another value. The select box won't reset the array instead of adding the option value in the end of array. Here's my code:
HTML:
<input type="text" name="ttc_list" id="ttc_list" />
<select name="priority_list" id="priority_list">
<option value="">Choose TTC First...</option>
</select>
Javascript:
$(document).ready(function(){
$("select#priority_list").attr("disabled","disabled");
$('input[name="ttc_list"]').change(function() {
var arr = [];
arr.length = 0;
var ttc = $("#ttc_list").val();
if(ttc == 100 || ttc == 101)
{
var prty100_Start = 40;
var prty100_End = 80;
while(prty100_Start < prty100_End+1){
arr.push(zeroPad(prty100_Start++,2));
}
}
else
{
var prty200_Start = 1;
var prty200_End = 5;
while(prty200_Start < prty200_End+1){
arr.push(zeroPad(prty200_Start++,2));
}
}
var selectOptions = {
100: arr,
101: arr,
200: arr,
204: arr,
210: arr
}
$("select#priority_list").removeAttr("disabled");
console.log($(this).val());
if(selectOptions[$(this).val()])
{
console.log(selectOptions[$(this).val()]);
$.each(selectOptions[$(this).val()], function() {
$('select[name="priority_list"]').append('<option>' + this + '</option>');
});
}
});
});
function zeroPad(num, numZeros) {
var n = Math.abs(num);
var zeros = Math.max(0, numZeros - Math.floor(n).toString().length );
var zeroString = Math.pow(10,zeros).toString().substr(1);
if( num < 0 ) {
zeroString = '-' + zeroString;
}
return zeroString+n;
}
Example: When user filled '100' in input text, it works fine in populating select box from '40' to '80', but when user changes the input text to '200' without refreshing the page, the select box show options from '40' to '80' and '01' to '05' instead of only '01' to '05'.
Expected result: When user changes the input text to '200' without refreshing the page, the select box shows options only from '01' to '05'
Here's my working demo http://jsfiddle.net/danc32/6UqYS/1/.
Where should I put my arr.length = 0 to reset my array?
Because you are using .append('<option>' + this + '</option>');, every time you change you add the new options to the existing list. Instead you could use:
.html('<option value="">Choose TTC First...</option>'); // remove old options
to reset the select and remove the old options, then use:
.append('<option>' + this + '</option>'); // add new options
to add the new ones.
See this JSFiddle for complete code.
You need to clear the contents of the select element before adding new items... also there is no need to recreate the selectOptions object within the change handler.. it is a static object so it can be created only once as given below
$(document).ready(function () {
var $priority_list = $("#priority_list").prop("disabled", true);
var selectOptions = {};
var arr_40_80 = arrays(40, 80);
selectOptions['100'] = arr_40_80;
selectOptions['101'] = arr_40_80;
var arr_1_5 = arrays(1, 5);
selectOptions['200'] = arr_1_5;
selectOptions['204'] = arr_1_5;
selectOptions['210'] = arr_1_5;
$('input[name="ttc_list"]').change(function () {
var ttc = $(this).val(), arr = selectOptions[ttc];
$priority_list.prop("disabled", false).empty();
if (arr) {
$.each(arr, function () {
$priority_list.append('<option>' + this + '</option>');
});
}
});
});
function arrays(start,end){
var arr = [];
while (start <= end) {
arr.push(zeroPad(start++, 2));
}
return arr;
}
function zeroPad(num, numZeros) {
var n = Math.abs(num);
var zeros = Math.max(0, numZeros - Math.floor(n).toString().length);
var zeroString = Math.pow(10, zeros).toString().substr(1);
if (num < 0) {
zeroString = '-' + zeroString;
}
return zeroString + n;
}
Demo: Fiddle

Iterate through a table using JavaScript to get values of specific cells

How can I iterate through a table using JavaScript to get the values of cells 4 and 5?
This is what I have:
function constructString() {
var table=document.getElementById('wcList');
for(var i=0; i<table.rows.length;i++){
var row = getElem(RowId + i);
var str_wc = table.rows[i].cells[1].firstChild.value;
var str_act = table.rows[i].cells[5].firstChild.value;
var str_coh = table.rows[i].cells[6].firstChild.value;
var str_mconf = table.rows[i].cells[7].firstChild.value;
var string1 = str_wc + row + str_act + row + str_coh + row + str_mconf + row;
}
}
Use innerHTML.
Try this:
function constructString() {
var table=document.getElementById('wcList');
for(var i=0; i<table.rows.length;i++){
// FIX THIS
var row = 0;
var str_wc=(table.rows[i].cells[1].innerHTML);
var str_act=(table.rows[i].cells[5].innerHTML);
var str_coh=(table.rows[i].cells[6].innerHTML);
var str_mconf=(table.rows[i].cells[7].innerHTML);
var string1=str_wc +row+str_act+row+str_coh+row+str_mconf+row;
alert(string1);
}
}

Javascript function not recognizing id in getElementById

I am adding a row to a table, and attached an ondblclick event to the cells. The function addrow is working fine, and the dblclick is taking me to seltogg, with the correct parameters. However, the var selbutton = document.getElementById in seltogg is returning a null. When I call seltogg with a dblclick on the original table in the document, it runs fine. All the parameters "selna" have alphabetic values, with no spaces, special characters, etc. Can someone tell me why seltogg is unable to correctly perform the document.getElementById when I pass the id from addrow; also how to fix the problem.
function addrow(jtop, sel4list, ron4list) {
var tablex = document.getElementById('thetable');
var initcount = document.getElementById('numrows').value;
var sel4arr = sel4list.split(",");
var idcount = parseInt(initcount) + 1;
var rowx = tablex.insertRow(1);
var jtop1 = jtop - 1;
for (j = 0; j <= jtop1; j++) {
var cellx = rowx.insertCell(j);
cellx.style.border = "1px solid blue";
var inputx = document.createElement("input");
inputx.type = "text";
inputx.ondblclick = (function() {
var curj = j;
var selna = sel4arr[curj + 2];
var cellj = parseInt(curj) + 3;
inputx.id = "cell_" + idcount + "_" + cellj;
var b = "cell_" + idcount + "_" + cellj;
return function() {
seltogg(selna, b);
}
})();
cellx.appendChild(inputx);
} //end j loop
var rowCount = tablex.rows.length;
document.getElementById('numrows').value = rowCount - 1; //dont count header
} //end function addrow
function seltogg(selna, cellid) {
if (selna == "none") {
return;
}
document.getElementById('x').value = cellid; //setting up for the next function
var selbutton = document.getElementById(selna); //*****this is returning null
if (selbutton.style.display != 'none') { //if it's on
selbutton.style.display = 'none';
} //turn it off
else { //if it's off
selbutton.style.display = '';
} //turn it on
} //end of function seltogg
You try, writing this sentence:
document.getElementById("numrows").value on document.getElementById('numrows').value
This is my part the my code:
contapara=(parseInt(contapara)+1);
document.getElementById("sorpara").innerHTML+="<li id=\"inputp"+contapara+"_id\" class=\"ui-state-default\"><span class=\"ui-icon ui-icon-arrowthick-2-n-s\"></span>"+$('#inputp'+contapara+'_id').val()+"</li>";
Look you have to use this " y not '.
TRY!!!!

Jquery change id, not working

I am using the following code to change the id of a div to something else, but it's not working??? Does anyone know why?
the if statement gives back a true so the div with the id of 'id' does exist but it's not running the actual line that changes the id
function grav_treasure(){
var i=0;
for(i=0;i<=treasure_list.length;i++){
var id = treasure_list[i];
if($("#"+id).length > 0){
var current_top = document.getElementById(id).style.top;
var current_top = parseFloat(current_top);
var id_split = id.split("_");
var row = id_split[2];
var row = parseFloat(row) + 1;
var col = id_split[5];
var col = parseFloat(col);
var block_id = "row_" + row + "_col_" + col + "_type_grass";
if($("#"+block_id).length > 0){
if(document.getElementById(block_id).getAttribute('class')=="block"){
}
else{
var rand_id=Math.floor(Math.random()*100);
var new_id = "treasure_grass_"+row+"_"+rand_id;
var new_id = new_id + "_col_" + col;
treasure_list.push(new_id);
if($("#"+id).length > 0){
alert(new_id);
$("#"+id).attr('id',new_id);
grav_treasure_tree(id, row);
}
}
}
else{
var rand_id=Math.floor(Math.random()*100);
var new_id = "treasure_grass_"+row+"_"+rand_id;
var new_id = new_id + "_col_" + col;
treasure_list.push(new_id);
if($("#"+id).length > 0){
alert(new_id);
$("#"+id).attr('id',new_id);
grav_treasure_tree(id, row);
}
}
}
}
setTimeout("grav_treasure()",100)
}
Sorry for anyone who tried to answer this, I made a small mistake by inputing a wrong variable into a function which screwed up everything, so there was actualy nothing wrong with the script above. Sorry :( but thanks for all your help!
$(document).ready(function(){
var id = "original";
var row = "some_row";
var col = "some_col"
var treasure_list = [];
var grav_treasure_tree = function(id, row){
// some code
}
var rand_id=Math.floor(Math.random()*100);
var new_id = "treasure_grass_"+row+"_"+rand_id;
new_id = new_id + "_col_" + col;
treasure_list.push(new_id);
if($("#"+id).length > 0){
alert(new_id);
$("#"+id).attr("id",new_id);
grav_treasure_tree(id, row);
}
});
That works if I have a div with id original:
<div id="original">
</div>
if($("#"+id).length > 0){
That checks to see if there is already an element on the page with the value of the "id" variable. I suspect that there is no such element at the time that code runs. That could be because
the value of "id" is not what you think it is;
the code runs at a point in time before the targeted element is part of the DOM

Categories

Resources