Javascript dynamic inputs calculation - javascript

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>

Related

Dynamically add set of from as many input in javascript

i want to make form as many as input text, i'm strugling to make a new form into the new div. if input is 3 then make 3 form, if input is 2 then input is just 2.
<input type="text" id="CountForm">
<form name="regis" id="regis" method="post" action="">
<input id="name1" name="name1" />
<input id="email1" name="email1" />
<input id="phone1" name="phone1" />
</form>
Is it this ?
var add = document.getElementById('button');
add.addEventListener('click', function(){
var num = parseInt(document.getElementById('CountForm').value);
var wrapper = document.querySelector('.wrapper');
wrapper.innerHTML = '';
for(var i =1; i<= num; i++){
var form =
`<form name="regis" id="regis${i}" method="post" action="">
<input id="name1" name="name1" />
<input id="email1" name="email1" />
<input id="phone1" name="phone1" />
</form>`
wrapper.innerHTML = wrapper.innerHTML + form;
}
})
<input type="text" id="CountForm" placeholder = "Enter form number">
<input type=button id = "button" value = "add">
<div class = "wrapper">
</div>
You can do like this as below
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
div{
padding:8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<title>jQuery add textbox example</title>
<body>
<h1>jQuery add textbox example</h1>
<body>
<form name="regis" id="regis" method="post" action="">
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='textbox' id='textbox1' >
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
</form>
</body>
You may Try For this:
var add = document.getElementById('button');
add.addEventListener('click', function(){
var num = parseInt(document.getElementById('CountForm').value);
var wrapper = document.querySelector('.wrapper');
wrapper.innerHTML = '';
for(var i =1; i<= num; i++){
var form =
`<form name="regis" id="regis${i}" method="post" action="">
<input id="name1" name="name1" placeholder="please enter name"/>
<input id="email1" name="email1" placeholder="please enter email" />
<input id="phone1" name="phone1" placeholder="please enter phone"/>
<input type="button" id="button12" name="button12" value="submit"/>
</form>`
wrapper.innerHTML = wrapper.innerHTML + form;
}
})
<input type="text" id="CountForm" placeholder = "Enter form number">
<input type=button id = "button" value = "add">
<div class = "wrapper">
</div>

I want to show alert message

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();" />

Operations on Javascript Array Element

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);

jQuery Dynamic Add Form Field, Remove Form Field

Hello I am trying to add new form field and delete form field after getting inspired from this tutorial - http://bootsnipp.com/snipps/dynamic-form-fields
My Current Problem is to delete and reset the value of all in chronological order.
<input type="hidden" name="count" value="1" />
<div class="control-group" id="fields">
<label class="control-label" for="field1">Nice Multiple Form Fields</label>
<div class="controls" id="profs">
<div class="input-append">
<input autocomplete="off" class="span3" id="field1" name="prof1" type="text" placeholder="Type something (it has typeahead too)" data-provide="typeahead" data-items="8"
data-source='["Aardvark","Beatlejuice","Capricorn","Deathmaul","Epic"]'/><button id="b1" onClick="addFormField()" class="btn btn-info" type="button">+</button>
</div>
<br /><small>Press + to add another form field :)</small>
</div>
</div>
Javascript :-
var next = 1;
function addFormField(){
var addto = "#field" + next;
next = next + 1;
var newIn = '<br /><br /><input autocomplete="off" class="span3" id="field' + next + '" name="field' + next + '" type="text" data-provide="typeahead" data-items="8"><button id="b1" onClick="$(this).parent().remove();" class="btn btn-info" type="button">+</button>';
var newInput = $(newIn);
$(addto).after(newInput);
$("#field" + next).attr('data-source',$(addto).attr('data-source'));
$("#count").val(next);
}
Parent Element is getting removed, but next counter is not reset properly. in hidden and all new created form :-
Only Add Demo :- http://bootsnipp.com/snipps/dynamic-form-fields
Add an Delete Demo with Bug :- http://jsfiddle.net/6dCrT/2/
Can someone help me please.
Thanks
Try:
function addFormField(){
var addto = "#field" + next;
next = next + 1;
var newIn = '<br /><br /><input autocomplete="off" class="span3" id="field' + next + '" name="field' + next + '" type="text" data-provide="typeahead" data-items="8"><button id="b'+next+'" onClick="$(this).prev().remove();$(this).remove();" class="btn btn-info" type="button">-</button>';
var newInput = $(newIn);
console.log(addto);
$(addto).after(newInput);
if(next>1)
$("button#b"+next).after(newInput);
$("#field" + next).attr('data-source',$(addto).attr('data-source'));
$("#count").val(next);
}
DEMO FIDDLE
In my example, I was building a form that would allow users to add multiple input names if they had more than one dog.
var counter = 0
jQuery(function () {
$(".newDog").click(function(){
counter ++;
if (counter < 4) {
var elem = $("<input/>",{
type: "text",
name: `dogname${counter}`
});
} else {
alert("You can only add 4 Dog Names")
}
var removeLink = $("<span/>").html("X").click(function(){
$(elem).remove();
$(this).remove();
counter --;
});
$(".dogname-inputs").append(elem).append(removeLink);
});
})
Full credit as mentioned to https://stackoverflow.com/users/714969/kevin-bowersox

On a iterative ajax call only last response showing. why?

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]);
}
});
}

Categories