Javascript error while calculating - javascript

I have a php simple program to calculate a textbox with another textbox, 1 years ago, there's no problem after now, I have problem with my JavaScript. It can't count my textbox.
My form code is here (without html tag, to minimize code in here):
<table>
<tr>
<td>Tol</td>
<td>:</td>
<td><input type="text" maxlength="11" name="tol" onkeydown="calculate()" value="0" /></td>
</tr>
<tr>
<td>Parkir</td>
<td>:</td>
<td><input type="text" maxlength="11" name="parkir" onkeydown="calculate()" value="0" /></td>
</tr>
<tr>
<td>Joki</td>
<td>:</td>
<td><input type="number" maxlength="11" name="joki" onkeydown="calculate();" value="0" /></td>
</tr>
<tr>
<td>Other</td>
<td>:</td>
<td><input type="number" name="other" maxlength="11" onkeydown="calculate();" value="0" /> <input type="text" name="othername" maxlength="50" /> </td>
</tr>
<tr>
<td>Total</td>
<td>:</td>
<td><input type="text" id="subtotal" onfocus="this.value = numberFormat(this.value);" name="subtotal" maxlength="100" value="0" />
<input type="text" id="totalbox" name="totalbox" maxlength="100" />
</td>
</tr>
</table>
and my JS script:
function calculate(){
var num1=document.myform.tol.value;
var num2=document.myform.parkir.value;
var num3=document.myform.joki.value;
var num4=document.myform.other.value;
var sum=parseFloat(num1)+parseFloat(num2)+parseFloat(num3)+parseFloat(num4);
document.getElementById('totalbox').value=sum.toString();
document.getElementById('subtotal').value=sum.toString();
}
can somebody correct my code or is there any update from JS that made my JS code doesn't work now?

Try using the onkeyup event instead of onkeydown. The onkeydown event fires before the value of your textbox reflects the input being typed in.

Try referencing the input boxes by id rather than by form.name:
function calculate(){
var num1=document.getElementById('tol').value;
var num2=document.getElementById('parkir').value;
var num3=document.getElementById('joki').value;
var num4=document.getElementById('other').value;
var sum=parseFloat(num1)+parseFloat(num2)+parseFloat(num3)+parseFloat(num4);
document.getElementById('totalbox').value=sum.toString();
document.getElementById('subtotal').value=sum.toString();
}
add the id attribute to your inputs:
<input type="text" maxlength="11" name="tol" id="tol" onkeydown="calculate()" value="0" />
...
You might also want to make your code a little more robust by checking to see if the element exists before trying to get the value:
function calculate(){
var fld1 = document.getElementById('tol');
var num1 = 0;
if (fld1 && fld1 != 'undefined') num1 = fld1.value;
...

Related

Need help for array field

This script works fine for me:
<script>
calculate = function(){
var resources = document.getElementById('a1').value;
var minutes = document.getElementById('a2').value;
document.getElementById('a3').value = parseInt(resources)* parseInt(minutes);
}
</script>
<form action="ProvideMedicinProcess.php" class="register" method="POST">
<table id="dataTable" border="1">
<tbody>
<tr>
<td><input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
<td><input type="datetime-local" required="required" name="VisitDate[]"></td>
<td>
<input class="form-control"type="text" required="required" placeholder="Symptoms" name="Symptoms[]">
</td>
<td>
<input class="form-control" type="text" required="required" placeholder="GivenMedicin" name="GivenMedicin[]">
</td>
<td>
<input id="a1" class="form-control" type="text" required="required" placeholder="UnitePrice" name="UnitePrice[]" onblur="calculate()" >
</td>
<td>
<input id="a2" class="form-control" type="text" required="required" placeholder="Quentity" name="Quentity[]" onblur="calculate()" >
</td>
<td>
<input id="a3" class="form-control" type="text" required="required" placeholder="SubTotal" name="SubTotal[]" >
</td>
</tr>
</tbody>
</table>
<input type="button" value="Add" onClick="addRow('dataTable')" />
<input type="button" value="Remove" onClick="deleteRow('dataTable')" />
<input class="submit" type="submit" value="Confirm" />
<input type="hidden" value="<?php echo $PatientIDSearch ?>" name="PatientIDSearch" />
</form>
But I need to calculate All Subtotal
Some issues:
If you add rows, you'll have to avoid that you get duplicate id property values in your HTML. It is probably easiest to just remove them and identify the input elements via their names, which does not have to be unique
It is bad practice to assign to a non-declared variable. Use var, and in the case of functions, you can just use the function calculate() { syntax.
Make the subtotal input elements read-only by adding the readonly attribute, otherwise the user can change the calculated total.
Instead of responding on blur events, you'll get a more responsive effect if you respond to the input event. And I would advise to bind the event handler via JavaScript, not via an HTML attribute.
I would fix some spelling errors in your elements (but maybe they make sense in your native language): Quantity with an 'a', UnitPrice without the 'e'.
You can use querySelectorAll to select elements by a CSS selector, and then Array.from to iterate over them.
See below snippet with 2 rows:
function calculate(){
var unitPrices = document.querySelectorAll('[name=UnitPrice\\[\\]]');
var quantities = document.querySelectorAll('[name=Quantity\\[\\]]');
var subTotals = document.querySelectorAll('[name=SubTotal\\[\\]]');
var grandTotal = 0;
Array.from(subTotals, function (subTotal, i) {
var price = +unitPrices[i].value * +quantities[i].value;
subTotal.value = price;
grandTotal += price;
});
// Maybe you can also display the grandTotal somehwere.
}
document.querySelector('form').addEventListener('input', calculate);
input { max-width: 7em }
<form action="ProvideMedicinProcess.php" class="register" method="POST">
<table id="dataTable" border="1">
<tbody>
<tr>
<td><input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
<td><input type="datetime-local" required="required" name="VisitDate[]"></td>
<td><input class="form-control" type="text" required="required" placeholder="Symptoms" name="Symptoms[]"></td>
<td><input class="form-control" type="text" required="required" placeholder="Given Medicin" name="GivenMedicin[]"></td>
<td><input class="form-control" type="text" required="required" placeholder="Unit Price" name="UnitPrice[]"></td>
<td><input class="form-control" type="text" required="required" placeholder="Quantity" name="Quantity[]"></td>
<td><input class="form-control" type="text" required="required" placeholder="SubTotal" readonly name="SubTotal[]" ></td>
</tr>
<tr>
<td><input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
<td><input type="datetime-local" required="required" name="VisitDate[]"></td>
<td><input class="form-control" type="text" required="required" placeholder="Symptoms" name="Symptoms[]"></td>
<td><input class="form-control" type="text" required="required" placeholder="Given Medicin" name="GivenMedicin[]"></td>
<td><input class="form-control" type="text" required="required" placeholder="Unit Price" name="UnitPrice[]"></td>
<td><input class="form-control" type="text" required="required" placeholder="Quantity" name="Quantity[]"" ></td>
<td><input class="form-control" type="text" required="required" placeholder="SubTotal" readonly name="SubTotal[]" ></td>
</tr>
</tbody>
</table>
</form>

Re-Using JavaScript Function

Creating a cake ordering form, and the # of cakes available can vary from month to month. I am attempting to tweak a JS function created from #Anderson Contreira but in my fiddle it does not work. Here is what I have thus far - Why does nothing change when I enter a quantity?
https://jsfiddle.net/2uack1w6/
Syntax
JS
function calculate(el){
var quantity = el.val();
var id = el.attr("id").replace("item_","").replace("_qty","");
var data = {quantity: quantity,id:id};
var targetTax = $("#item_"+id+"_tax");
var targetTotalPrice = $("#item_"+id+"_totalprice");
$.post($.post(window.alert("It's been one or two or three entered");
});
}
var qty = $("#item_1_qty");
var qty1 = $("#item_2_qty");
var qty2 = $("#item_3_qty");
qty.on("keyup",function(){
window.alert("It's been one or two or three entered");
});
HTML/PHP
<body>
<form id="Form1" runat="server">
<div id="Form1" runat="server">
<table id="table1" border="1">
<tr>
<th>Item</th>
<th>Price</th>
<th>Quantity</th>
<th>Tax</th>
<th>Total</th>
</tr>
<tr>
<td><label for="lblChoccake">Choc Cake</label></td>
<td><label for="lblitem1price">$25.00</label></td>
<td><input type="text" id="item_1_qty" name="txtitem1qty" value="0" maxlength="10" size="3"></td>
<td><input type ="text" id="item_1_tax" name="txtitem1tax" maxlength="10" size="3" readonly></td>
<td><input type="text" id="item_1_totalprice" name="txtitem1totalprice" maxlength="10" size="3" readonly></td>
</tr>
<tr>
<td><label for="lblLemonFudgecake">Lemon Fudge Cake</label></td>
<td><label for="lblitem2price">$15.00</label></td>
<td><input type="text" id="item_2_qty" name="txtitem1qty" value="0" maxlength="10" size="3"></td>
<td><input type ="text" id="item_2_tax" name="txtitem1tax" maxlength="10" size="3" readonly></td>
<td><input type="text" id="item_2_totalprice" name="txtitem1totalprice" maxlength="10" size="3" readonly></td>
</tr>
<tr>
<td><label for="lblCoconut">Coconut Cake</label></td>
<td><label for="lblitem3price">$35.00</label></td>
<td><input type="text" id="item_3_qty" name="txtitem1qty" value="0" maxlength="10" size="3"></td>
<td><input type ="text" id="item_3_tax" name="txtitem1tax" maxlength="10" size="3" readonly></td>
<td><input type="text" id="item_3_totalprice" name="txtitem1totalprice" maxlength="10" size="3" readonly></td>
</tr>
</table>
</div>
</form>
</body>
jQuery(function($) {
var qty = $("#item_1_qty");
var qty1 = $("#item_2_qty");
var qty2 = $("#item_3_qty");
qty.on("keyup",function(){
alert("It's been one or two or three entered");
});
});
Try this, you are assigning variables before the document has actually loaded.
Take a look here: https://jsfiddle.net/andersoncontreira/mtu6syby/1/
You can make some changes and will work well:
Add a class in each input of item_?_qty e.g.: <input type="text" id="item_1_qty" class="item_qty" />
In your javascript, you can leave the call generic:
jQuery(document).ready(function(){
//you can use a class for help you
$(".item_qty").on("keyup",function(){
//window.alert("It's been one or two or three entered");
calculate($(this));
});
});

issues in html when calling 2 javascript functions at a time

I have an HTML file related to a javascript file.
In this javascript file, I have 3 functions which 2 of them will be called onload of the body.
These 2 functions are meant to type a string, each of them in a different textarea.
But, when Testing this, the two strings that are typed by these js functions, are unreadable
To clarify my issue: the string must be like this:
verification step 3 of 4 passed…
enter serial number
when I call the 2 functions onload of the body, it gives me this:
vrfcto f4pse..
ne eilnme..
I can't find the issue in my code.
HTML CODE
<!DOCTYPE HTML>
<html>
<head>
<title>Webmaster's Top Secret Directory</title>
<link rel="stylesheet" href="index.css">
<script src="redirector5.js"></script>
</head>
<body background="camouflage.jpg" onload='write()'>
<div align="center">
<img src="header.png" alt="Warning"/>
</div><br><br><br><br><br><br>
<div id="container">
<form name="form1" onsubmit="return myFunction();">
<div><table align="center" class="table">
<tr><td>
<input type="text" class="inputtext2" name="text" value="open sesame" disabled /></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" value="identify yourself...." disabled /></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" value="omar saab" disabled /></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" value="verification step 1 of 4 passed.... enter secret phrase...." disabled /></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" value="i own you terminal. release security now and let me in" disabled /></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" value="verifying.... verification step 2 of 4 passed.... enter your purpose of entrance...." disabled /></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" value="manage personal files" disabled /></td>
</tr>
<tr>
<td><textarea class="inputtext2222" id='screen' disabled></textarea></td>
</tr>
<tr>
<td><textarea class="inputtext2222" id='screen2' disabled></textarea></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" id="myTextarea" autofocus spellcheck="false" /></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" disabled/></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" disabled/></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" disabled/></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" disabled/></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" disabled/></td>
</tr>
<tr>
<td><input type="text" class="inputtext2" disabled/></td>
</tr>
</table>
</div>
<input
type="submit"
name="submit">
</form>
</div>
</body>
</html>
JAVASCRIPT CODE
function myFunction() {
var x = document.getElementById("myTextarea").value;
if (x === "tango-whisky-70433863") {
document.location.href = "index6.html";
return false;
}
else {
alert('Command not found.\nYou are not supposed to be here.\nGet out now !');
return false;
}
}
function write(){
type();
type2();
}
var index = 0;
var text = 'verification 3 of 4 passed...';
function type()
{
document.getElementById('screen').innerHTML += text.charAt(index);
index += 1;
var t = setTimeout('type()',80);
}
var index = 0;
var text2 = 'enter serial number....';
function type2()
{
document.getElementById('screen2').innerHTML += text2.charAt(index);
index += 1;
var t = setTimeout('type2()',80);
}
NOTE When I call one of these 2 functions apart, it works.
I could be wrong, but I think that the issue is with index. You have the same variable name for each type, and when they run at the same time, it confuses the script. You have a variable named index, that will +=1, so when the next function gets it, it is messed up.
Try changing the variable for index on type2() to index2. See if this fixes it.
You have tried to declare the variable index twice. Try renaming it in the second function and it should work fine.
Explanation:
you declare var index = 0; twice within the same scope. in this case the second declaration is what gets used(fiddle example), and so there is only index variable inside the functions. That's why each function displays every second letter.

Javascript onChange sum input after percentage

<form name="cost">
<table border="1">
<tr>
<td>Cost</td>
<td><input type="text" name="cost" /></td>
</tr>
<tr>
<td>Discount</td>
<td><input type="text" name="discount" /> (<span id="discount2"></span>)%</td>
</tr>
<tr>
<td>Net Cost</td>
<td><input type="text" name="net" /></td>
</tr>
</table>
</form>
Hello guys,
I really need a help of javascript programming. The process of the form are:
Put a number of in Cost
Then put a number of discount (auto calculates span#discount2=cost*discount/100)
Net cost auto update = Cost-Discount
I tried many times but have no luck plus lack of javascript knowledge. Please help.
First, create a function to do that
function calculateDiscount()
{
var cost = document.getElementById('cost').value;
var discount = document.getElementById('discount').value;
//do the math
var net = cost-discount;
//update
document.getElementById('discount2').innerHTML = cost*(discount/100);
document.getElementById('net').value = net;
}
You'll also need to update your html, to add ID's to all elements and also call the function
<form name="cost">
<table border="1">
<tr><td>Cost</td><td><input type="text" id="cost" name="cost" onChange="calculateDiscount(); return false;" /></td></tr>
<tr><td>Discount</td><td><input onChange="calculateDiscount(); return false;" type="text" id="discount" name="discount" /> (<span id="discount2"></span>)%</td></tr>
<tr><td>Net Cost</td><td><input type="text" name="net" id="net" /></td></tr>
</table>
</form>

Is it posible to get all the values of the text boxes with the same name?

I have a doubt in javascript. Is it posible to get the values of text boxes with the same name ?
for example
<INPUT TYPE="text" NAME="inputbox" VALUE="">
<INPUT TYPE="text" NAME="inputbox" VALUE="">
these text boxes have same name, how can i get its values by name ?
OK, lemme come to the real problem i got, hope am explaining correctly.
I have a series of text boxes which i gotta validate now. Its not a big deal to validate textboxe normally.
But this is an array of text boxes where the id of the text boxes will be available only when the fields are added dynamically by clicking on the + button. when the press button is clicked the whole set of text boxes will appear. as many times its clicked, it will get added.
So its imposible to get the values to validate with the ID, so i tried by name.
JAVASCRIPT FUNCTION
function insComep()
{
// $("#doctorPri").validationEngine("updatePromptsPosition")
// jQuery("#doctorPri").validationEngine('attach', {promptPosition : "topRight"});
rl=document.getElementById("compeTable").rows.length;
var a=document.getElementById("compeTable").insertRow(rl);
var g=a.insertCell(0);
var f=a.insertCell(1);
var m=a.insertCell(2);
var n=a.insertCell(3);
var o=a.insertCell(4);
var p=a.insertCell(5);
var q=a.insertCell(6);
var r=a.insertCell(7);
var s=a.insertCell(8);
var t=a.insertCell(9);
//var v=a.insertCel1l(11);
//var u=a.insertCell(12);
g.innerHTML='<select name="competproduct[]" style="width:86px" id="competproduct'+rl+'" class="validate[required]" ><option value="">--Select--</option><?echo $product_str;?></select>';
f.innerHTML='<input type="text" name="competcompany[]" id="competcompany'+rl+'" size="10" class="validate[required]" >';
m.innerHTML='<input type="text" name="competbrand[]" id="competbrand'+rl+'" size="10" class="validate[required]" >';
n.innerHTML='<input type="text" name="competdrug[]" id="competdrug'+rl+'" size="10" class="validate[required]" >';
o.innerHTML='<input type="text" name="competquty[]" id="competquty'+rl+'" size="2" class="validate[required,custom[integer]] text-input" >';
p.innerHTML='<input type="text" name="competprice_frm[]" id="competprice_frm'+rl+'" size="2" class="validate[required,custom[number],funcCall[getPriceFromE]] text-input" />';
q.innerHTML='<input type="text" name="competprice_to[]" id="competprice_to'+rl+'" size="2" class="validate[required,custom[number],funcCall[getPriceTo]] text-input" />';
r.innerHTML='<input type="text" name="competmrp[]" id="competmrp'+rl+'" size="2" class="validate[required,custom[number],funcCall[getMrp]] text-input"/>';
s.innerHTML='<select name="ChemistParma[]" style="width:86px" id="ChemistParma'+rl+'" style="width:86px" ><option value="">--Select--</option><?echo $chemist_str;?></select>';
t.innerHTML='<img src="media/images/details_close.png" onClick="delCompe('+rl+'); "/>';
// jQuery("#doctorPri").validationEngine('attach', {promptPosition : "topRight"});
$("#doctorPri").validationEngine('hideAll');
}
HTML
<table width="100%" id='compeTable' border='0' style='margin-left:auto;margin-right:auto;margin-top:40px;' >
<tr style="border-bottom:1px solid #999999;"><td colspan='4'>
<div style="background:;padding:3px;text-align:left; ">
<font color='black'><strong >Competitor Detail(s):</strong></font><font color="red">*</font>
</div>
</td></tr>
<tr>
<td>Product Name:<font color="red">*</font></td>
<td>Company Name:<font color="red">*</font></td>
<td>Brand Name:<font color="red">*</font></td>
<td>Drug Name:<font color="red">*</font></td>
<td> Quantity:<font color="red">*</font></td>
<td>Pricefrom Dist:<font color="red">*</font></td>
<td >Price to Dist:<font color="red">*</font></td>
<td> MRP:<font color="red">*</font></td>
<td>Chemist<font color="red">*</font><input type='button'value='+' style='width:1px' style='width:1px' onclick='frame5()'/>
</td>
<td></td>
</tr>
<tr><td> </td></tr>
<tr>
<td>
<select name='competproduct[]' id='competproduct' style="width:86px" class="validate[required]" >
<option value=''>-select Product-</option>
<? echo $product_str;?>
</select>
</td>
<td>
<input type="text" name="competcompany[]" id="competcompany" size="10" class="validate[required]" >
</td>
<td ><input type="text" name="competbrand[]" id="competbrand" size="10" class="validate[required]" >
</td>
<td><input type="text" name="competdrug[]" id="competdrug" size="10" class="validate[required]" >
</td>
<td><input type="text" name="competquty[]" id="competquty" size="2" class="validate[required,custom[integer]] text-input" >
</td>
<td>
<input type="text" name="competprice_frm[]" id="competprice_frm" size="2" class="validate[required,custom[number],funcCall[getPriceFromE]] text-input" />
</td>
<td>
<input type="text" name="competprice_to[]" id="competprice_to" size="2" class="validate[required,custom[number],funcCall[getPriceTo]] text-input" />
</td>
<td><input type="text" name="competmrp[]" id="competmrp" size="2" class="validate[required,custom[number],funcCall[getMrp]] text-input" onBlur=''/>
</td>
<td>
<select name='ChemistParma[]' id='ChemistParma' style="width:86px">
<option value=''>-select chemict-</option>
<?echo $chemist_str?>
</select></td>
<td>
<img src="media/images/details_open.png" onClick="insComep()"/>
</td>
</tr>
</table>
It's quite simple,
document.getElementsByName("inputBox");
You can use a multitude of different methods.
1) Manual traversal of childNodes etc, and checking for nodeName. This is pretty involved and requires a lot of boring code, so I won't write an example of that here.
2) document.getElementsByTagName. This can also be used on DOM nodes, so you can do something like document.getElementById("my_form").getElementsByTagName("input"), depending on how the rest of the DOM looks of course.
3) document.querySelectorAll("input"). The string argument is a full CSS selector. Some older browsers doesn't support this though.
Here is example for you with your code:
<div id="inputs">
<INPUT TYPE="text" NAME="inputbox" VALUE="asd">
<INPUT TYPE="text" NAME="inputbox" VALUE="efs">
</div>
<script>
$(document).ready(function () {
var howmany = $('#inputs').children("input").length;
alert(howmany);
for( i=0; i<= howmany-1; i++ ) {
var input = $("#inputs").children("input").eq(i).attr('VALUE');
alert(input);
}
});
</script>

Categories

Resources