On a Java EE application i have the following on click function
function calculateK() {
var matD = "" + $('.dr1c1').val() + "__" + $('.dr1c2').val() + "__" + $('.dr1c3').val()
+ "__" + $('.dr2c1').val() + "__" + $('.dr2c2').val() + "__" + $('.dr2c3').val()
+ "__" + $('.dr3c1').val() + "__" + $('.dr3c2').val() + "__" + $('.dr3c3').val();
var h = '5';
var it = 0;
var cellB = '';
var cellJ = '';
var cellK = '';
for (it = 1; it < 5; it++) {
cellB = '.b' + it;
cellJ = '.jc' + it;
cellK = '.k' + it;
var bb1 = $(cellB + 'r1c1').val();
var bb2 = $(cellB + 'r1c2').val();
var bb3 = $(cellB + 'r2c1').val();
var bb4 = $(cellB + 'r2c2').val();
var bb5 = $(cellB + 'r3c1').val();
var bb6 = $(cellB + 'r3c2').val();
var jj = $(cellJ).val();
$.ajax({
url: '/M08CDECUStructuralOptimiser/ServletMatrix1?action=calculateJ',
data: {matrixB: "" + bb1 + "__" + bb2 + "__" + bb3 + "__" + bb4 + "__" + bb5 + "__" + bb6, matrixD: matD, valJ: jj},
dataType: "json",
success: function(response) {
$(cellK+'1').val(response[0]);
$(cellK+'2').val(response[1]);
$(cellK+'3').val(response[2]);
$(cellK+'4').val(response[3]);
$(cellK+'5').val(response[4]);
$(cellK+'6').val(response[5]);
$(cellK+'7').val(response[6]);
$(cellK+'8').val(response[7]);
$(cellK+'9').val(response[8]);
}
});
}
}
On the servlet
try {
if (action.compareTo("calculateJ") == 0) {
String matrixStringB = request.getParameter("matrixB");
String[] tempStringArray;
tempStringArray = matrixStringB.split("__");
double[][] array = {{Double.parseDouble(tempStringArray[0]), Double.parseDouble(tempStringArray[1])},
{Double.parseDouble(tempStringArray[2]), Double.parseDouble(tempStringArray[3])},
{Double.parseDouble(tempStringArray[4]), Double.parseDouble(tempStringArray[5])}};
Matrix b = new Matrix(array);
Matrix bT = b.transpose();
Matrix c = b.times(bT);
//System.out.println(Arrays.deepToString(c.getArray()));
String matrixStringD = request.getParameter("matrixD");
String[] tempStringArray2;
tempStringArray2 = matrixStringD.split("__");
double[][] arrayD = {{Double.parseDouble(tempStringArray2[0]), Double.parseDouble(tempStringArray2[1]), Double.parseDouble(tempStringArray2[2])},
{Double.parseDouble(tempStringArray2[3]), Double.parseDouble(tempStringArray2[4]), Double.parseDouble(tempStringArray2[5])},
{Double.parseDouble(tempStringArray2[6]), Double.parseDouble(tempStringArray2[7]), Double.parseDouble(tempStringArray2[8])}};
Matrix d = new Matrix(arrayD);
Matrix r1 = c.times(d);
String matrixStringJ = request.getParameter("valJ");
double valj = Double.parseDouble(matrixStringJ);
Matrix r2 = r1.times(valj);
double valh = 1.5;
Matrix r3 = r2.times(valh);
double[][] resultArray = r3.getArray();
double[] oneDArray = new double[resultArray.length * resultArray.length];
//Flatten 2D array to 1D array...
int s = 0;
for (int i = 0; i < resultArray.length; i++) {
for (int j = 0; j < resultArray.length; j++) {
oneDArray[s] = resultArray[i][j];
s++;
}
}
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(oneDArray);
//System.out.println(oneDArray.length);
System.out.println(Arrays.deepToString(r3.getArray()));
out.println(json);
}
} finally {
}
Now on the console i am getting all 4 array and there value properly but on the site only the last k value is showing k41,k42,.......k49
How to fix this?
when i try the js loop as limit it<2 it shows the k11,k12,......k19 value properly.
Html:
<div class="showK" >
<table>
<tr>
<td>
K1
</td>
<td>
<input type="text" class="k11" value="" />
<input type="text" class="k12" value="" />
<input type="text" class="k13" value="" />
<br />
<input type="text" class="k14" value="" />
<input type="text" class="k15" value="" />
<input type="text" class="k16" value="" />
<br />
<input type="text" class="k17" value="" />
<input type="text" class="k18" value="" />
<input type="text" class="k19" value="" />
<br />
</td>
</tr>
<tr>
<td>
K2
</td>
<td>
<input type="text" class="k21" value="" />
<input type="text" class="k22" value="" />
<input type="text" class="k23" value="" />
<br />
<input type="text" class="k24" value="" />
<input type="text" class="k25" value="" />
<input type="text" class="k26" value="" />
<br />
<input type="text" class="k27" value="" />
<input type="text" class="k28" value="" />
<input type="text" class="k29" value="" />
<br />
</td>
</tr>
<tr>
<td>
K3
</td>
<td>
<input type="text" class="k31" value="" />
<input type="text" class="k32" value="" />
<input type="text" class="k33" value="" />
<br />
<input type="text" class="k34" value="" />
<input type="text" class="k35" value="" />
<input type="text" class="k36" value="" />
<br />
<input type="text" class="k37" value="" />
<input type="text" class="k38" value="" />
<input type="text" class="k39" value="" />
<br />
</td>
</tr>
<tr>
<td>
K4
</td>
<td>
<input type="text" class="k41" value="" />
<input type="text" class="k42" value="" />
<input type="text" class="k43" value="" />
<br />
<input type="text" class="k44" value="" />
<input type="text" class="k45" value="" />
<input type="text" class="k46" value="" />
<br />
<input type="text" class="k47" value="" />
<input type="text" class="k48" value="" />
<input type="text" class="k49" value="" />
<br />
</td>
</tr>
</table>
</div>
The ajax call is asynchronous, so when it receives the response of the server the value of the variable cellB, cellK, cellK already were changed in the loop.
The solution for that is to add the call inside a function like the example below when invoke the function doAjaxCall.
function calculateK() {
var matD = "" + $('.dr1c1').val() + "__" + $('.dr1c2').val() + "__" + $('.dr1c3').val()
+ "__" + $('.dr2c1').val() + "__" + $('.dr2c2').val() + "__" + $('.dr2c3').val()
+ "__" + $('.dr3c1').val() + "__" + $('.dr3c2').val() + "__" + $('.dr3c3').val();
var h = '5';
var it = 0;
var cellB = '';
var cellJ = '';
var cellK = '';
for (it = 1; it < 5; it++) {
cellB = '.b' + it;
cellJ = '.jc' + it;
cellK = '.k' + it;
doAjaxCall(cellB, cellJ, cellK);
}
}
function doAjaxCall(cellB, cellJ, cellK){
var bb1 = $(cellB + 'r1c1').val();
var bb2 = $(cellB + 'r1c2').val();
var bb3 = $(cellB + 'r2c1').val();
var bb4 = $(cellB + 'r2c2').val();
var bb5 = $(cellB + 'r3c1').val();
var bb6 = $(cellB + 'r3c2').val();
var jj = $(cellJ).val();
$.ajax({
url: '/M08CDECUStructuralOptimiser/ServletMatrix1?action=calculateJ',
data: {matrixB: "" + bb1 + "__" + bb2 + "__" + bb3 + "__" + bb4 + "__" + bb5 + "__" + bb6, matrixD: matD, valJ: jj},
dataType: "json",
success: function(response) {
$(cellK+'1').val(response[0]);
$(cellK+'2').val(response[1]);
$(cellK+'3').val(response[2]);
$(cellK+'4').val(response[3]);
$(cellK+'5').val(response[4]);
$(cellK+'6').val(response[5]);
$(cellK+'7').val(response[6]);
$(cellK+'8').val(response[7]);
$(cellK+'9').val(response[8]);
}
});
}
Related
As a result of the script execution, I have a combined string concatenation of two, how to make the first part of the resulting line colored red, and the second blue
function generateFullName() {
var elem1 = document.getElementById('fName').value;
var elem2 = document.getElementById('lName').value;
document.getElementById('fullName').innerText = elem1 + ' ' + elem2;
}
First Name
<param type="text" id="fName" onkeyup="generateFullName()" class='tsvet' value="2" /><br/> Last Name
<param type="text" id="lName" onkeyup="generateFullName()" value="354" /><br/> Full Name <span id="fullName" class='tsvet' />
<body onload="generateFullName();"> </body>
Use innerHTML instead innerText
function generateFullName() {
var elem1 = document.getElementById('fName').value;
var elem2 = document.getElementById('lName').value;
document.getElementById('fullName').innerHTML = '<span style="color:red">' + elem1 + '</span><span style="color:blue"> ' + elem2 + '</span>';
}
First Name
<param type="text" id="fName" onkeyup="generateFullName()" class='tsvet' value="2" /><br/> Last Name
<param type="text" id="lName" onkeyup="generateFullName()" value="354" /><br/> Full Name <span id="fullName" class='tsvet' />
<body onload="generateFullName();"> </body>
I have this script that adds the 4 numbers together but JS doesn't take into account the original decimal places.
// Initial input form
<form class="weight_form" data-ajax="false" method="post">
<input type="text" class="input_save" placeholder="save as.."/>
<input type="text" id="lf" placeholder="enter LF lbs" value="" onkeyup="myFunction()"/>
<input type="text" id="rf" placeholder="enter RF lbs" value="" onkeyup="myFunction()"/>
<input type="text" id="lr" placeholder="enter LR lbs" value="" onkeyup="myFunction()"/>
<input type="text" id="rr" placeholder="enter RR lbs" value="" onkeyup="myFunction()"/>
<input type="submit" id="sub_save" value="save"/>
// Section to display results
<div id="bottom_section">
<input type="text" id="total" value=""/>
<input type="text" id="cross" value=""/>
<input type="text" id="ls" value=""/>
<input type="text" id="bite" value=""/>
</div>
// JS script to perform action on the fly
<script>
function myFunction() {
var lf = document.getElementById("lf");
var rf = document.getElementById("rf");
var lr = document.getElementById("lr");
var rr = document.getElementById("rr");
var lf = parseInt(lf.value);
var rf = parseInt(rf.value);
var lr = parseInt(lr.value);
var rr = parseInt(rr.value);
var lf_1 = lf*1;
var rf_1 = rf*1;
var lr_1 = lr*1;
var rr_1 = rr*1;
var total = lf_1 + rf_1 + lr_1 + rr_1;
var cross = rf_1 + lr_1 / total;
var ls = lf_1 + lr_1 / total;
var bite = lr_1 - rr_1;
$('#total').val(total);
$('#cross').val(Math.round(cross));
$('#ls').val(Math.round(ls));
$('#bite').val(bite);
};
</script>
If I enter say 20.5 for each input in the "weight_form" (lf, rf, lr, rr) the total is 80 instead of 82. Why does it seem to always round down the value?
To handle floats in your form, use parseFloat instead of parseInt, when parsing your values from the input elements.
Since you're using jQuery, you can simplify myFunction by selecting your fields and parse their values in one line:
var lf = parseFloat($("#lf").val());
var rf = parseFloat($("#rf").val());
var lr = parseFloat($("#lr").val());
var rr = parseFloat($("#rr").val());
Example:
function myFunction() {
var lf = parseFloat($("#lf").val());
var rf = parseFloat($("#rf").val());
var lr = parseFloat($("#lr").val());
var rr = parseFloat($("#rr").val());
var lf_1 = lf * 1;
var rf_1 = rf * 1;
var lr_1 = lr * 1;
var rr_1 = rr * 1;
var total = lf_1 + rf_1 + lr_1 + rr_1;
var cross = rf_1 + lr_1 / total;
var ls = lf_1 + lr_1 / total;
var bite = lr_1 - rr_1;
$('#total').val(total);
$('#cross').val(Math.round(cross));
$('#ls').val(Math.round(ls));
$('#bite').val(bite);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form class="weight_form" data-ajax="false" method="post">
<input type="text" class="input_save" placeholder="save as.." />
<input type="text" id="lf" placeholder="enter LF lbs" value="" onkeyup="myFunction()" />
<input type="text" id="rf" placeholder="enter RF lbs" value="" onkeyup="myFunction()" />
<input type="text" id="lr" placeholder="enter LR lbs" value="" onkeyup="myFunction()" />
<input type="text" id="rr" placeholder="enter RR lbs" value="" onkeyup="myFunction()" />
<input type="submit" id="sub_save" value="save" />
<div id="bottom_section">
<input type="text" id="total" value="" />
<input type="text" id="cross" value="" />
<input type="text" id="ls" value="" />
<input type="text" id="bite" value="" />
</div>
</form>
This is running good, but i want to show alert message if sum of all input value not equal to hundred and stop on same page.
function doMath(){
// Capture the entered values of two input boxes
var my_input1 = document.getElementById('my_input1').value;
var my_input2 = document.getElementById('my_input2').value;
var my_input3 = document.getElementById('my_input3').value;
var my_input4= document.getElementById('my_input4').value;
var my_input5 = document.getElementById('my_input5').value;
var my_input6 = document.getElementById('my_input6').value;
// Add them together and display
var sum = parseInt(my_input1) + parseInt(my_input2) + parseInt(my_input3) + parseInt(my_input4) + parseInt(my_input5) + parseInt(my_input6);
document.write(sum);
}
<input type="text" id="my_input1" /></br>
<input type="text" id="my_input2" /></br>
<input type="text" id="my_input3" /></br>
<input type="text" id="my_input4" /></br>
<input type="text" id="my_input5" /></br>
<input type="text" id="my_input6" />
<input type="button" value="Add Them Together" onclick="doMath();" />
Here is another solution
function _get(ID){
return document.getElementById(ID);
}
function doMath(){
var my_input1 = _get('my_input1').value ? parseInt(_get('my_input1').value) : 0;
var my_input2 = _get('my_input2').value ? parseInt(_get('my_input2').value) : 0;
var my_input3 = _get('my_input3').value ? parseInt(_get('my_input3').value) : 0;
var my_input4 = _get('my_input4').value ? parseInt(_get('my_input4').value) : 0;
var my_input5 = _get('my_input5').value ? parseInt(_get('my_input5').value) : 0;
var my_input6 = _get('my_input6').value ? parseInt(_get('my_input6').value) : 0;
// Add them together and display
var sum = my_input1 + my_input2 + my_input3 + my_input4 + my_input5 + my_input6;
if(sum==100){
alert('Sum is = 100');
/*YOUR CODE HERE*/
}else if(sum<100){
alert('Sum is less than 100');
/*YOUR CODE HERE*/
}else if(sum>100){
alert('Sum is bigger than 100');
/*YOUR CODE HERE*/
}
}
<input type="text" id="my_input1" /></br>
<input type="text" id="my_input2" /></br>
<input type="text" id="my_input3" /></br>
<input type="text" id="my_input4" /></br>
<input type="text" id="my_input5" /></br>
<input type="text" id="my_input6" />
<input type="button" value="Add Them Together" onclick="doMath();" />
Here is the details about Conditional (ternary) Operator
If I clearly understood what you want, you can try this:
var sum = parseInt(my_input1) + parseInt(my_input2) + parseInt(my_input3) + parseInt(my_input4) + parseInt(my_input5) + parseInt(my_input6);
if (sum != 100) {
alert('Different from a hundred')
return false;
}
I used return false in case you want to handle the result and take some other action.
You can use alert() function to display alert popup
if(sum!=100){
alert("Sum is not equal to 100");
}else{
document.write(sum);
}
Please refer working snippet
function doMath()
{
// Capture the entered values of two input boxes
var my_input1 = document.getElementById('my_input1').value;
var my_input2 = document.getElementById('my_input2').value;
var my_input3 = document.getElementById('my_input3').value;
var my_input4= document.getElementById('my_input4').value;
var my_input5 = document.getElementById('my_input5').value;
var my_input6 = document.getElementById('my_input6').value;
// Add them together and display
var sum = parseInt(my_input1) + parseInt(my_input2) + parseInt(my_input3) + parseInt(my_input4) + parseInt(my_input5) + parseInt(my_input6);
if(sum!=100){
alert("Sum is not equal to 100");
}else{
document.write(sum);
}
}
<input type="text" id="my_input1" /></br>
<input type="text" id="my_input2" /></br>
<input type="text" id="my_input3" /></br>
<input type="text" id="my_input4" /></br>
<input type="text" id="my_input5" /></br>
<input type="text" id="my_input6" />
<input type="button" value="Add Them Together" onclick="doMath();" />
Replace
document.write(sum);
with
if(sum==100) {
document.write(sum);
} else {
alert("show your messaage");
}
function doMath()
{
// Capture the entered values of two input boxes
var my_input1 = document.getElementById('my_input1').value;
var my_input2 = document.getElementById('my_input2').value;
var my_input3 = document.getElementById('my_input3').value;
var my_input4= document.getElementById('my_input4').value;
var my_input5 = document.getElementById('my_input5').value;
var my_input6 = document.getElementById('my_input6').value;
// Add them together and display
var sum = parseInt(my_input1) + parseInt(my_input2) + parseInt(my_input3) + parseInt(my_input4) + parseInt(my_input5) + parseInt(my_input6);
if(sum >= 100){
document.write(sum);
}
else{
alert("sum is less than 100")
}
}
<input type="text" id="my_input1" /></br>
<input type="text" id="my_input2" /></br>
<input type="text" id="my_input3" /></br>
<input type="text" id="my_input4" /></br>
<input type="text" id="my_input5" /></br>
<input type="text" id="my_input6" />
<input type="button" value="Add Them Together" onclick="doMath();" />
With the following code, in the function placeOrder() I cannot get the calculations to work using the price[] array elements and the chairAmtA(and the following amount variables I have). It always returns the answer as NaN. What is wrong with the code and how do I fix it?
<title>
Ryan Weiland, Assignment 2
</title>
<!--Load stylesheet-->
<link rel="stylesheet" type="text/css" href="assignment2.css">
<!--Load description variables-->
<script type="text/javascript" src="script.js" >
</script>
<script>
<!--Initilize variables for calculations-->
var chairCost = 50;
var deskCost = 150;
var rockerCost = 250;
var tableCost = 200;
var ftstlCost = 75;
var fname;
var lname;
var streetName;
var cityName;
var state;
var zip;
var phoneOne;
var phoneTwo;
var phoneThree;
var chairAmt;
var deskAmt;
var rockerAmt;
var tableAmt;
var ftstlAmt;
function orderTotal(){
//window.alert("This Function Works");
//Personal Information
var fname = document.items.first.value;
var lname = document.items.last.value;
var streetName = document.items.street.value;
var cityName = document.items.city.value;
var state = document.items.state.value;
var zip = document.items.zipCode.value;
var phoneOne = document.items.pOne.value;
var phoneTwo = document.items.pTwo.value;
var phoneThree = document.items.pThree.value;
//Item Aomount
chairAmt = document.items.chairs.value;
deskAmt = document.items.desks.value;
rockerAmt = document.items.rockers.value;
tableAmt = document.items.tables.value;
ftstlAmt = document.items.ftstls.value;
//Calculations
//Chair Total
var costChairT = chairAmt*chairCost;
//Desk Total
var costDeskT = deskAmt*deskCost;
//Rocker Total
var costRockerT = rockerAmt*rockerCost;
//Table Total
var costTableT = tableAmt*tableCost;
//Footstool Total
var costFtstlT = ftstlAmt*ftstlCost;
//Overall Total Cost
var totalCost = costChairT + costDeskT + costRockerT + costTableT + costFtstlT;
//Personal Total
var personalTotal = fname + " " + lname + "\n" + streetName + ", \n" + cityName + " " + state + ", \n" + zip + "\nPhone Number: " + phoneOne + "- " + phoneTwo + "- " +phoneThree + "\n";
//New window with everything retrieved
window.alert(personalTotal + "Total Cost: $" + totalCost);
}
function placeOrder(chairsAmt, desksAmt, rockersAmt, tablesAmt, ftstlsAmt) {
//window.alert("placeOrder runs");
var order = [];
//Prices in array
var prices = [50, //Chair
150, //Desk
250, //Rocking Chair
200, //Table
75]; //Footstool
//Personal Information
order[0] = document.items.first.value;
order[1] = document.items.last.value;
order[2] = document.items.street.value;
order[3] = document.items.city.value;
order[4] = document.items.state.value;
order[5] = document.items.zipCode.value;
order[6] = document.items.pOne.value;
order[7] = document.items.pTwo.value;
order[8] = document.items.pThree.value;
//Item Aomount
var chairAmtA = document.items.chairs.value;
var deskAmtA = document.items.desks.value;
var rockerAmtA = document.items.rockers.value;
var tableAmtA = document.items.tables.value;
var ftstlAmtA = document.items.ftstls.value;
var prices = "Prices\nChair: " + prices[0] + "\nDesk: " + prices[1] + "\nRocking Chair: " + prices[2] + "\nTable: " + prices[3] + "\nFootstool: " + prices[4] + "\n\n";
//Chair Total
var chairCostA = chairAmtA * prices[0];
//Desk Total
var deskCostA = deskAmtA * prices[1];
//Rocker Total
var rockerCostA = rockerAmtA * prices[2];
//Table Total
var tableCostA = tableAmtA * prices[3];
//Footstool Total
var ftstlCostA = ftstlAmtA * prices[4];
//Overall Total Cost
var totalCostA = chairCostA + deskCostA + rockerCostA + tableCostA + ftstlCostA;
//Personal Total
personalTotalA= order[0] + " " + order[1] + "\n"
+ order[2] + ", " + order[3] + "\n"
+ order[4] + ", " + order[5] + "\n"
+ "Phone Number: " + order[6] + "-" + order[7] + "-" + order[8] + "\n\n";
//Quantity ordered
var quantity = "Chairs Ordered: " + chairAmtA + "\nDesks Ordered: " + deskAmtA + "\nRocking Chairs Ordered: " + rockerAmtA + "\nTables Ordered: " + tableAmtA + "\nFootstools Ordered: " + ftstlAmtA + "\n\n";
//New window with everything retrieved
var x = window.confirm(personalTotalA + quantity + prices + "\nTotal Cost: $" + totalCostA);
if(x ==true)
window.alert("Your order has been placed!");
else
window.alert("Your order has been cancled.");
}
</script>
<h1>Swanson's Woodworking</h1>
<h2>Customer Order Form</h2>
<br />
<!--List of items-->
<form name="items">
<br />
<br />
<!--Chair-->
Click the button for a description.
<input type="radio" name="items" onclick="document.item.itemDesc2.value=chairDesc" />
<b>Chair($50)</b>
<br />
<!--Desk-->
Click the button for a description.
<input type="radio" name="items" onclick="document.item.itemDesc2.value=deskDesc" />
<b>Desk($150)</b>
<br />
<!--Rocking Chair-->
Click the button for a description.
<input type="radio" name="items" onclick="document.item.itemDesc2.value=rockerDesc" />
<b>Rocking Chair($250)</b>
<br />
<!--Table-->
Click the button for a description.
<input type="radio" name="items" onclick="document.item.itemDesc2.value=tableDesc" />
<b>Table($200)</b>
<br />
<!--Footstool-->
Click the button for a description.
<input type="radio" name="items" onclick="document.item.itemDesc2.value=ftstlDesc" />
<b>Footstool($75)</b>
<br />
<!--Textarea for descriptions-->
<p>
<textarea name="itemDesc2" cols="30" rows="5" style="background-color: transparent; border: 1; font-size:20px; overflow: hidden; color: #5e0000">
</textarea>
</p>
<!--Information Form-->
<!--Personal Information-->
First Name: <input type="text" name="first">
<br /><br />
Last Name : <input type="text" name="last">
<br /><br />
Street Address:<input type="text" name="street">
<br /><br />
City: <input type="text" name="city">
<br /><br />
State: <input type="text" name="state">
<br /><br />
Zip Code: <input type="text" name="zipCode">
<br /><br />
Phone Number: (<input type="text" name="pOne" size="3">) - <input type="text" name="pTwo" size="3"> - <input type="text" name="pThree" size="4">
<br /><br />
<!--List of items-->
Chairs Desired: <input type="number" name="chairs">
<br /><br />
Desks Desired: <input type="number" name="desks">
<br /><br />
Rocking Chairs Desired: <input type="number" name="rockers">
<br /><br />
Tables Desired: <input type="number" name="tables">
<br /><br />
Footstools Desired: <input type="number" name="ftstls">
<br /><br />
</form>
<!--Calculate your total order.-->
<input type = "button" onclick = "orderTotal()" value = "Calculate your total order" > <!--Button for total-->
<br /><br >
<input type = "button" onclick = "placeOrder()" value = "Place Order" > <!--Button for total-->
Looks like youre trying to subtract two strings:
console.log("12"-"13");
You need to convert all inputs ( they are strings) to numbers:
val=input.value.toNumber();
Or:
val=(+input.value);
I have a form which is dynamic and it calculates duration time. I can insert rows by clicking on Add a new row.
My problem starts from the second row which can not be calculated because it is dynamic. Could you please help me with that.
Thanks
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var FieldCount = 1; //to keep track of text box added
var x = 1; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
FieldCount++;
wrapper.append('From → <input type="text" name="fromhours" id="fromhours' + FieldCount + '" onblur="cal()" /> : <input type="text" name="fromminutes" id="fromminutes' + FieldCount + '" onblur="cal()" /> | To → <input type="text" name="tohours" id="tohours' + FieldCount + '" onblur="cal()" /> : <input type="text" name="tominutes" id="tominutes' + FieldCount + '" onblur="cal()" /> | Result → <input type="text" name="resulthours" id="resulthours' + FieldCount + '" /> : <input type="text" name="resultminutes" id="resultminutes' + FieldCount + '" /><br /><br />'); //add input box
}
});
wrapper.on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
function cal() {
var fromhours = parseInt(document.getElementById('fromhours').value) * 60;
var fromminutes = parseInt(document.getElementById('fromminutes').value);
var tohours = parseInt(document.getElementById('tohours').value) * 60;
var tominutes = parseInt(document.getElementById('tominutes').value);
var resultfrom = fromhours + fromminutes;
var resultto = tohours + tominutes;
var result = resultto - resultfrom;
var hourresult = parseInt(result / 60);
var minutesresult = (result - (hourresult * 60));
document.getElementById('resulthours').value = '0' + hourresult.toFixed(0);
document.getElementById('resultminutes').value = ('0' + minutesresult).slice(-2);
}
input[type=text] {
width: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input style="margin-left:28px;" type="image" class="add_field_button" value="Add a new row" />
<br />From →
<input type="text" name="fromhours" id="fromhours" onblur="cal()" />:
<input type="text" name="fromminutes" id="fromminutes" onblur="cal()" />| To →
<input type="text" name="tohours" id="tohours" onblur="cal()" />:
<input type="text" name="tominutes" id="tominutes" onblur="cal()" />| Result →
<input type="text" name="resulthours" id="resulthours" />:
<input type="text" name="resultminutes" id="resultminutes" />
<br />
<br />
<div class="input_fields_wrap"></div>
My problem is from the second row I can't get my result to work
You need to refer the current element row id by adding x as follows
wrapper.append('From →
<input type="text" name="fromhours" id="fromhours' + FieldCount + '" onblur="cal(x)" /> ...
function cal(x) {
var fromhours = parseInt(document.getElementById('fromhours'+x).value) * 60;
...
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var FieldCount = 1; //to keep track of text box added
var x = 1; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
FieldCount++;
wrapper.append('From → <input type="text" name="fromhours" id="fromhours' + FieldCount + '" onblur="cal('+FieldCount +')" /> : <input type="text" name="fromminutes" id="fromminutes' + FieldCount + '" onblur="cal('+FieldCount +')" /> | To → <input type="text" name="tohours" id="tohours' + FieldCount + '" onblur="cal('+FieldCount +')" /> : <input type="text" name="tominutes" id="tominutes' + FieldCount + '" onblur="cal('+FieldCount +')" /> | Result → <input type="text" name="resulthours" id="resulthours' + FieldCount + '" /> : <input type="text" name="resultminutes" id="resultminutes' + FieldCount + '" /><br /><br />'); //add input box
}
});
wrapper.on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
function cal(x) {
x=x||"";
var fromhours = parseInt(document.getElementById('fromhours'+x).value) * 60;
var fromminutes = parseInt(document.getElementById('fromminutes'+x).value);
var tohours = parseInt(document.getElementById('tohours'+x).value) * 60;
var tominutes = parseInt(document.getElementById('tominutes'+x).value);
var resultfrom = fromhours + fromminutes;
var resultto = tohours + tominutes;
var result = resultto - resultfrom;
var hourresult = parseInt(result / 60);
var minutesresult = (result - (hourresult * 60));
document.getElementById('resulthours'+x).value = '0' + hourresult.toFixed(0);
document.getElementById('resultminutes'+x).value = ('0' + minutesresult).slice(-2);
}
input[type=text] {
width: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input style="margin-left:28px;" type="image" class="add_field_button" value="Add a new row" />
<br />From →
<input type="text" name="fromhours" id="fromhours" onblur="cal()" />:
<input type="text" name="fromminutes" id="fromminutes" onblur="cal()" />| To →
<input type="text" name="tohours" id="tohours" onblur="cal()" />:
<input type="text" name="tominutes" id="tominutes" onblur="cal()" />| Result →
<input type="text" name="resulthours" id="resulthours" />:
<input type="text" name="resultminutes" id="resultminutes" />
<br />
<br />
<div class="input_fields_wrap"></div>
I am not a JS expert, but could it have something to do with the fact, that you refer to the rows under the same ID attribute? As far as I can see you're not specifying to the code which one of the rows to calculate.
See #Bellash answer for a possible solution
You forgot to pass the fieldCount number inside the cal() function and concatenate it with the field ids, so the cal() function always used the first row of text fields.
I've corrected your snippet for you.
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var FieldCount = 1; //to keep track of text box added
var x = 1; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
FieldCount++;
wrapper.append('From → <input type="text" name="fromhours" id="fromhours' + FieldCount + '" onblur="cal(' + FieldCount + ')" /> : <input type="text" name="fromminutes" id="fromminutes' + FieldCount + '" onblur="cal(' + FieldCount + ')" /> | To → <input type="text" name="tohours" id="tohours' + FieldCount + '" onblur="cal(' + FieldCount + ')" /> : <input type="text" name="tominutes" id="tominutes' + FieldCount + '" onblur="cal(' + FieldCount + ')" /> | Result → <input type="text" name="resulthours" id="resulthours' + FieldCount + '" /> : <input type="text" name="resultminutes" id="resultminutes' + FieldCount + '" /><br /><br />'); //add input box
}
});
wrapper.on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
function cal(fieldCount) {
console.log(arguments);
var fromhours = parseInt(document.getElementById('fromhours' + fieldCount).value) * 60;
var fromminutes = parseInt(document.getElementById('fromminutes' + fieldCount).value);
var tohours = parseInt(document.getElementById('tohours' + fieldCount).value) * 60;
var tominutes = parseInt(document.getElementById('tominutes' + fieldCount).value);
var resultfrom = fromhours + fromminutes;
var resultto = tohours + tominutes;
var result = resultto - resultfrom;
var hourresult = parseInt(result / 60);
var minutesresult = (result - (hourresult * 60));
document.getElementById('resulthours' + fieldCount).value = '0' + hourresult.toFixed(0);
document.getElementById('resultminutes' + fieldCount).value = ('0' + minutesresult).slice(-2);
}
input[type=text] {
width: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input style="margin-left:28px;" type="image" class="add_field_button" value="Add a new row" />
<br />From →
<input type="text" name="fromhours" id="fromhours1" onblur="cal(1)" />:
<input type="text" name="fromminutes" id="fromminutes1" onblur="cal(1)" />| To →
<input type="text" name="tohours" id="tohours1" onblur="cal(1)" />:
<input type="text" name="tominutes" id="tominutes1" onblur="cal(1)" />| Result →
<input type="text" name="resulthours" id="resulthours1" />:
<input type="text" name="resultminutes" id="resultminutes1" />
<br />
<br />
<div class="input_fields_wrap"></div>
You have to get the unique id and use that in your calculations. In the JS I replaced the function with an on keyup and added a statement to prevent the NaN
JS
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var FieldCount = 1; //to keep track of text box added
var x = 1; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
FieldCount++;
wrapper.append('From → <input type="text" class="cal" name="fromhours" id="fromhours' + FieldCount + '" /> : <input type="text" class="cal" name="fromminutes" id="fromminutes' + FieldCount + '" /> | To → <input type="text" class="cal" name="tohours" id="tohours' + FieldCount + '" /> : <input type="text" class="cal" name="tominutes" id="tominutes' + FieldCount + '" /> | Result → <input type="text" class="cal" name="resulthours" id="resulthours' + FieldCount + '" /> : <input type="text" class="cal" name="resultminutes" id="resultminutes' + FieldCount + '" /><br /><br />'); //add input box
}
});
wrapper.on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
$('body').on('keyup', '.cal', function () {
var id = $(this).attr('id').substr(-1),
fromhours = ~~$('#fromhours' + id).val(),
fromminutes = ~~$('#fromminutes' + id).val(),
tohours = ~~$('#tohours' + id).val(),
tominutes = ~~$('#tominutes' + id).val();
if (fromhours != '' && fromminutes != '' && tohours != '' && tominutes != '') {
var resultfrom = (fromhours * 60) + fromminutes,
resultto = (tohours * 60) + tominutes,
result = resultto - resultfrom,
hourresult = ~~(result/60),
minuteresult = ~~(result - hourresult * 60);
$('#resulthours' + id).val(hourresult);
$('#resultminutes' + id).val(minuteresult);
}
});
HMTL
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input style="margin-left:28px;" type="image" class="add_field_button" value="Add a new row" />
<br />From →
<input type="text" class="cal" name="fromhours" id="fromhours1" />:
<input type="text" class="cal" name="fromminutes" id="fromminutes1" /> | To →
<input type="text" class="cal" name="tohours" id="tohours1" />:
<input type="text" class="cal" name="tominutes" id="tominutes1" /> | Result →
<input type="text" class="cal" name="resulthours" id="resulthours1" />:
<input type="text" class="cal" name="resultminutes" id="resultminutes1" />
<br />
<br />
<div class="input_fields_wrap"></div>