Adding to a value declared in another function - javascript

It is hard to explain, you can see a DEMO HERE
I have a products table that dynamically creates/deletes new lines of products. I also have a totals table that totals up the totals of each line together.
In that totals box, I have a travel box I want to add to the grand total, but the issue I am having is the travel input is outside the table that is totaling all the values. I can replace the total with a new total, but I can not seem to call the sub total, add the travel and output a grand total.
HTML
<table class="order-details">
<tbody>
<tr>
<td><input type="text" value="" name="" placeholder="Work Description" class="wei-add-field description 1"/></td>
<td><input type="text" value="" name="" placeholder="QTY" class="wei-add-field quantity 1" /></td>
<td><input type="text" value="" name="" placeholder="$0.00" class="wei-add-field unit-price 1"/></td>
<td><input type="text" value="" name="" placeholder="$0.00" class="wei-add-field price-total 1" id=""/></td>
<td> </td>
</tr>
</tbody>
</table>
<div class="wei-add-service">Add Item</div>
<table class="wei-add-totals">
<tr>
<td width="50%">Sub Total</td>
<td width="50%" class="wie-add-subtotal"> </td>
</tr>
<tr class="alternate travel">
<td>Travel</td>
<td><input type="text" value="" placeholder="0.00" class="wei-add-field travel" /></td>
</tr>
<tr>
<td>Taxes</td>
<td><input type="text" value="" placeholder="0.00" class="wei-add-field wie-total-taxes" id="wei-disabled" disabled/> </td>
</tr>
<tr class="alternate total">
<td>Total</td>
<td><input type="text" value="" placeholder="0.00" class="wei-add-field wie-grand-total" id="wei-disabled" disabled/></td>
</tr>
</table>
Javascript
var counter = 1;
var testArray = [ 2,3,4,5];
jQuery('a.wei-add-service-button').click(function(event){
event.preventDefault();
counter++;
var newRow = jQuery('<tr><td><input type="text" class="wei-add-field description ' + counter + '"/></td><td><input type="text" class="wei-add-field quantity ' + counter + '" /></td><td><input type="text" class="wei-add-field unit-price ' + counter + '"/></td><td><input type="text" value="" name="" placeholder="$0.00" class="wei-add-field price-total ' + counter + '" id=""/></td><td>X</td></tr>');
jQuery('table.order-details').append(newRow);
});
jQuery('table.order-details').on('click','tr a',function(e){
e.preventDefault();
var table = $(this).closest('table');
jQuery(this).parents('tr').remove();
reCalculate.call( table );
});
jQuery('table.order-details').on("keyup", "tr", reCalculate);
function reCalculate() {
var grandTotal = 0;
jQuery(this).closest('table').find('tr').each(function() {
var row = jQuery(this);
var value = +jQuery( ".unit-price", row ).val();
var value2 = +jQuery( ".quantity", row ).val();
var total = value * value2;
grandTotal += total;
jQuery( ".wei-add-field.price-total", row ).val( '$' + total.toFixed(2) );
});
jQuery(".wie-add-subtotal").text( '$' + grandTotal.toFixed(2));
}

I don't think, given the task of creating this, I would have chosen to do it in the way you did.
However, using your existing code you can bind the Travel value on change, paste, or keyup and run a function on any of those actions. Within that function I have removed the special character ($) from ".wie-grand-total" using a regex and converted the value of ".wie-grand-total" to a float using parseFloat. I also converted the Travel value to a float using parseFloat. I then added them together and made the sum your new value for "wie-grand-total".
/* NEW SINCE COMMENTS */
//Add to your HTML New table
<table class="order-details">
<tbody>
<tr>
<td><input type="text" value="" name="" placeholder="Work Description" class="wei-add-field description 1"/></td>
<td><input type="text" value="" name="" placeholder="QTY" class="wei-add-field quantity 1" /></td>
<td><input type="text" value="" name="" placeholder="$0.00" class="wei-add-field unit-price 1"/></td>
<td><input type="text" value="" name="" placeholder="$0.00" class="wei-add-field price-total 1" id=""/></td>
/* NEW SINCE COMMENTS*/
<td><input type="text" id="travelHid" value=""></td>
<td> </td>
</tr>
</tbody>
</table>
/* NEW SINCE COMMENTS */
$('#travelHid').hide();
var travelVal = 0;
function updateTravelVal(travelVal){
var travelVal = travelVal;
$('#travelHid').val(travelVal);
};
updateTravelVal();
$("#travelVis").bind("change paste keyup", function() {
var noChars = jQuery(".wie-grand-total").val().replace(/[^0-9.]/g, "");
var newTot = parseFloat(noChars) + parseFloat($(this).val());
jQuery(".wie-grand-total").val( '$' + newTot.toFixed(2));
//added error checking
var checkError = jQuery(".wie-grand-total").val( '$' + newTot.toFixed(2));
//if the value that would go in input is NaN then use travelVal
//since there is no value in .wie-grand-total yet
if (typeof checkError !== "string") {
jQuery(".wie-grand-total").val( '$' + travelVal.toFixed(2))
} else if (typeof checkError === "string") {
jQuery(".wie-grand-total").val( '$' + newTot.toFixed(2))
}
/* NEW SINCE COMMENTS */
updateTravelVal(travelVal);
});
A fiddle for demonstration (now with hiddenVal per comment)
http://jsfiddle.net/chrislewispac/wed6eog0/3/
Only potential problems here are it only runs when you change, paste, or key up the value in #TravelVis.
/EXPLAINED SINCE COMMENTS/
It the html I added a td with input. Input id="travelHid". I then make that invisible by applying jQuery method .hide(). I then exposed travelVal to global scope an initiated it with a value of zero then created a function to update that value.
Within that function I set the value to the argument travelVal or to 0 if there are no args. I then immediately call it.
Then, I added a call to that function with the arg travelVal from our bind function to update it if a value is present.
And finally:
Just add a row to the table with preset value of Travel and Quant 1.
http://jsfiddle.net/chrislewispac/xntn7p5p/5/

Related

Rewriting JavaScript code with consequent numbers in the names of ids

I'm trying to apply a function to input field with ids that contain consequent numbers (ie. price1, price2, price3), etc.
There's no problem with the first row of field that are defined for a start. But further input fields are dynamically added by a jQuery function and their number is not known in advance.
I hoped it would be an easy loop to apply:
var i=1;
$("#quantity"+i).keyup(function() {
var price= $("#price"+i).val();
var quantity= $(this).val();
var value= price*quantity;
var value=value.toFixed(2); /* rounding the value to two digits after period */
value=value.toString().replace(/\./g, ',') /* converting periods to commas */
$("#value"+i).val(value);
});
So far so good - the outcome of the multiplication properly displays in the id="value1" field after the "quantity" field is filled up.
Now further fields should follow the pattern and calculate the value when the quantity is entered - like this:
[price2] * [quantity2] = [value2]
[price3] * [quantity3] = [value3]
etc.
So the code follows:
$('#add_field').click(function(){ /* do the math after another row of fields is added */
var allfields=$('[id^="quantity"]');
var limit=(allfields.length); /* count all fields where id starts with "quantity" - for the loop */
for (var count = 2; count < limit; count++) { /* starting value is now 2 */
$("#quantity"+count).keyup(function() {
var cena = $("#price"+count).val();
var quantity= $("#quantity"+count).val();
var value= price*quantity;
var value=value.toFixed(2);
value=value.toString().replace(/\./g, ',')
$("#value"+count).val(value);
});
}
});
The problem is that all further "value" fields are only calculated when "quantity2" is (re)entered and the "value2" is not calculated at all.
I guess there's a mistake while addressing fields and/or triggering the calculation.
How should I correct the code?
Just in case the "add_field" function is needed to solve the problem:
$(document).ready(function(){
var i=1;
$('#add_field').click(function(){
i++;
$('#offer').append('<tr id="row'+i+'">
<td><input type="text" name="prod_num[]" id="prod_num'+i+'" placeholder="Product number (6 digits)"></td><td><input type="text" name="prod_name[]" disabled></td>
<td><input type="text" name="cena[]" id="price'+i+'" placeholder="Enter your price"></td>
<td><input type="text" name="quantity[]" id="quantity'+i+'" placeholder="Enter quantity"></td>
<td><input type="text" name="value[]" id="value'+i+'" disabled></td>
<td><button type="button" name="remove_field" id="'+i+'" class="button_remove">X</button></td></tr>');
});
Incrementing IDs is a lot more trouble than it is worth, especially when you start removing rows as well as adding them.
This can all be done using common classes and traversing within the specific row instance.
To account for future rows use event delegation.
Simplified example:
// store a row copy on page load
const $storedRow = $('#myTable tr').first().clone()
// delegate event listener to permanent ancestor
$('#myTable').on('input', '.qty, .price', function(){
const $row = $(this).closest('tr'),
price = $row.find('.price').val(),
qty = $row.find('.qty').val();
$row.find('.total').val(price*qty)
});
$('button').click(function(){
// insert a copy of the stored row
// delegated events will work seamlessly on new rows also
const $newRow = $storedRow.clone();
const prodName = 'Product XYZ';// get real value from user input
$newRow.find('.prod-name').text(prodName)//
$('#myTable').append($newRow)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Add row</button>
<table id="myTable">
<tr>
<td class="prod-name">Product 1</td>
<td>Qty:<input type="number" class="qty" value="0"></td>
<td>Price:<input type="number" class="price" value="0"></td>
<td>Total:<input type="text" class="total" value="0" readonly></td>
</tr>
<tr>
<td class="prod-name">Product 2</td>
<td>Qty:<input type="number" class="qty" value="0"></td>
<td>Price:<input type="number" class="price" value="0"></td>
<td>Total:<input type="text" class="total" value="0" readonly></td>
</tr>
</table>
Understanding Event Delegation
The first thing to consider is that you can get the length of a selector. So for example:
var count = $("input").length;
If there is one, value here would be 1. if there are four, the value would be 4.
You can also use .each() option to itereate each of the items in the selector.
$('#add_field').click(function(){
var allFields = $('[id^="quantity"]');
allFields.each(function(i, el){
var c = i + 1;
$(el).keyup(function() {
var price = parseFloat($("#price" + c).val());
var quantity = parseInt($(el).val());
var value = price * quantity;
value = value.toFixed(2);
value = value.toString().replace(/\./g, ',');
$("#value" + c).val(value);
});
});
});
You could also create relationship based on the ID itself.
$(function() {
function calcTotal(price, qnty) {
return (parseFloat(price) * parseInt(qnty)).toFixed(2);
}
$('#add_field').click(function() {
var rowClone = $("#row-1").clone(true);
var c = $("tbody tr[id^='row']").length + 1;
rowClone.attr("id", "row-" + c);
$("input:eq(0)", rowClone).val("").attr("id", "prod_num-" + c);
$("input:eq(1)", rowClone).val("").attr("id", "price-" + c);
$("input:eq(2)", rowClone).val("").attr("id", "quantity-" + c);
$("input:eq(3)", rowClone).val("").attr("id", "value-" + c);
$("button", rowClone).attr("id", "remove-" + c);
rowClone.appendTo("table tbody");
});
$("table tbody").on("keyup", "[id^='quantity']", function(e) {
var $self = $(this);
var id = $self.attr("id").substr(-1);
if ($("#price-" + id).val() != "" && $self.val() != "") {
$("#value-" + id).val(calcTotal($("#price-" + id).val(), $self.val()));
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add_field">Add Field</button>
<br />
<h2>Product</h2>
<table>
<thead>
<tr>
<td>Number</td>
<td>Name</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
<td></td>
</thead>
<tbody>
<tr id="row-1">
<td><input type="text" name="prod_num[]" id="prod_num-1" placeholder="Product number (6 digits)"></td>
<td><input type="text" name="prod_name[]" disabled></td>
<td><input type="text" name="cena[]" id="price-1" placeholder="Enter your price"></td>
<td><input type="text" name="quantity[]" id="quantity-1" placeholder="Enter quantity"></td>
<td><input type="text" name="value[]" id="value-1" disabled></td>
<td><button type="button" name="remove_field" id="remove-1" class="button_remove">X</button></td>
</tr>
</tbody>
</table>

parseInt() functionis not working

I have a input element to accept number type. I know javascript takes input as a string. so I am using parseInt() to convert into integer. but it is not working.
My code is:
<tr>
<td rowspan="6"><br><br><br><br><br>B1<br> Salary/Pension:</td>
<td>(1) Salary (excluding all allowances, perquisites and profit in lieu of salary</td>
<td><input type="text" id="sal" value="0" name="sal" placeholder="" class="form-control "></td>
</tr>
<tr>
<td>(2) Allowances not exempt</td>
<td><input type="text" id="allowance" value="0" name="allowance" placeholder="" class="form-control "></td>
</tr>
<tr>
<td>(3)Value of perquisites</td>
<td><input type="text" id="perquisites" value="0" name="perquisites" placeholder="" class="form-control "></td>
</tr>
<tr>
<td>(4) Profits in lieu of salary</td>
<td><input type="text" id="profit" name="profit" value="0" placeholder="" class="form-control"></td>
</tr>
<tr>
<td>(5)Deduction u/s 16</td>
<td><input type="text" id="ded16" name="ded16" value="0" placeholder="" class="form-control"></td>
</tr>
<tr>
<td>(6)Income chargable under the head 'Salaries':</td>
<td><input type="text" id="inchargesal" value="0" name="inchargesal" placeholder="" class="form-control" readonly></td>
</tr>
//js part is:
$(document).ready(function() {
function change() {
f = a + b + c + d - e;
alert(f);
$('#inchargesal').removeAttr('readonly').val(f);
}
$('#sal').on('change', function() {
var a = parseInt(document.getElementsById("sal").value);
alert("hi");
change();
});
$('#allowance').on('change', function() {
b = parseInt(document.getElementById("allowance").value)
change();
});
$('#perquisites').on('change', function() {
c = parseInt(document.getElementsById("perquisites").value);
change();
});
$('#profit').on('change', function() {
d = parseInt(document.getElementsById("profit").value);
change();
});
$('#ded16').on('change', function() {
e = parseInt(document.getElementsById("ded16").value);
change();
});
});
here to notice is, when I use alert("hi") above the parseInt statement then alert works fine, however when I use it after that, alert("hi") doesn't work.
what's going wrong? please help.
You are using incorrect method of document. There is no such method saying getElementsById(). In HTML DOM the id field is unique so it can never be getElements but getElement. Use getElementById('id') to make it work.
Also its always better to check console first where most of your problems can be resolved on your own.
Console -

Comparing readonly value with a value entered by a user

I have table which have available quantity value of a readonly and a quantity entered by a user. I check if the available quantity is more than what the user entered. If value entered by user is more than available quantity I tell the user to enter value less than available quantity. The first entered quantity value gets validated correctly. I get problem when the user enter second quantity. How can I tackle this? I use availableQuantity and quantity as my id's
Here is my code HTML
<div id="makeOrders">
<table id="myDatatable" class="display datatable">
<thead>
<tr>
<th>Part No</th>
<th>Description</th>
<th>Model No</th>
<th>Available QTY</th>
<th>Tick To Order</th>
<th>Quantity</th>
<!-- <th>Edit</th> -->
</tr>
</thead>
<tbody>
<!-- Iterating over the list sent from Controller -->
<c:forEach var="list" items="${compatibility}">
<tr>
<td>${list.partNumber}</td>
<td>${list.itemDescription}</td>
<td>${list.compitableDevice}</td>
<td><input type="number" id="avaliableQuantity"
name="avaliableQuantity" class="form-control" readonly="readonly"
value="${list.quantity}"></td>
<td><input type="checkbox" class="form-group"
id="checkedOrder" name="selectedItem"
value="${list.partNumber},${list.compitableDevice},${list.itemDescription}"></td>
<td><input type="number" id="quantity" name="quantity"
class="form-control" onblur="compareQuantity()" value="" /></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
This my JavaScript code
<script type="text/javascript">
/*Compare available quantity with entered quantity*/
function compareQuantity() {
var ourAvaliableQuantity = document.getElementById("avaliableQuantity").value;
var yourQuantity = document.getElementById("quantity").value;
if ( ourAvaliableQuantity > yourQuantity ) {
alert("Your quantity (" +yourQuantity+ ") is less or equal to available quantity (" + ourAvaliableQuantity+ ") order.\n You can now place your order");
console.log("True,",yourQuantity + " is less than " + ourAvaliableQuantity);
console.log("Place an Order");
}else if(ourAvaliableQuantity < yourQuantity) {
alert("Your order quantity (" +yourQuantity+ ") can not be greater than available quantity (" + ourAvaliableQuantity+ "). \n Please enter less quantity");
document.getElementById("quantity").value = "";
console.log("False,",ourAvaliableQuantity + " is small than " + yourQuantity);
console.log("You can not place an order, enter less quantity");
console.log("Enter value between 1 till " +ourAvaliableQuantity+ " not more than " +ourAvaliableQuantity);
}
}
</script>
The id attribute specifies a unique id for an HTML element, it must must be unique within the HTML document. try use the id concatenating an unique value from the 'list' variable. Or pass the '${list.quantity}' to the function.
<c:forEach var="list" items="${compatibility}">
<tr>
<td>${list.partNumber}</td>
<td>${list.itemDescription}</td>
<td>${list.compitableDevice}</td>
<td><input type="text" id="${list.partNumber}_avaliableQuantity"
name="avaliableQuantity" class="form-control" readonly="readonly"
value="${list.quantity}"></td>
<td><input type="checkbox" class="form-group"
id="checkedOrder" name="selectedItem"
value="${list.partNumber},${list.compitableDevice},${list.itemDescription}"></td>
<td><input type="text" id="${list.partNumber}_quantity" name="quantity"
class="form-control" onblur="compareQuantity(this, ${list.quantity})" value="" /></td>
</tr>
</c:forEach>
And in your javascript
function compareQuantity(element, availableQuantity) {
if (availableQuantity >= element.value){
....
You may only have one ID per page. Develop a name scheme such that you don't have two or more id="availableQuantity" or id="quantity" on the page. For instance:
<tr>
<td>${list.partNumber}</td>
<td>${list.itemDescription}</td>
<td>${list.compitableDevice}</td>
<td><input type="text" id="avaliableQuantity-1" name="avaliableQuantity" class="form-control" readonly="readonly" value="${list.quantity}"></td>
<td><input type="checkbox" class="form-group" id="checkedOrder" name="selectedItem" value="${list.partNumber},${list.compitableDevice},${list.itemDescription}"></td>
<td><input type="text" id="quantity-1" name="quantity" class="form-control" onblur="compareQuantity()" value="" /></td>
</tr>
<tr>
<td>${list.partNumber}</td>
<td>${list.itemDescription}</td>
<td>${list.compitableDevice}</td>
<td><input type="text" id="avaliableQuantity-2" name="avaliableQuantity" class="form-control" readonly="readonly" value="${list.quantity}"></td>
<td><input type="checkbox" class="form-group" id="checkedOrder" name="selectedItem" value="${list.partNumber},${list.compitableDevice},${list.itemDescription}"></td>
<td><input type="text" id="quantity-2" name="quantity" class="form-control" onblur="compareQuantity()" value="" /></td>
</tr>
1) A document should only have one element with each ID, so maybe you want to use classes or data- attributes to find the available quantity. For example, you could add 'data-available-quantity' on the element, and then you can just check this with this.dataset.availableQuantity.
2) You don't need to look up the element because you can just pass it when onBlur is called, like
<input type="text" onblur="checkQuantity(this)" data-available-quantity="25" name="quantity" ...
and then your function looks like
function checkQuantity(element) {
if (parseInt(element.dataset.availableQuantity) < parseInt(element.value()))
// this is where you add a message
(edit: added parseInt to make sure they're all integers)

Using jQuery to validate value in comparison to other input value

So I have a base Hour input field and I'm trying to validate the other input fields so that once the base hour is added the other input values can only be as large as the first base rate Hours column (first input). Or put another way the one input field becomes the max number value once it is entered. So if the base is 12 for the Hours column the second and third rate can be no larger than 12. The tricky part is add new row feature means all new rows for the hour column have to adhere to the rule as well. I have been trying to figure it out for a bit, any help would be appreciated.
Here is the fiddle: http://jsfiddle.net/uuzhuom9/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#calculate').on('click', function() {
$('.hours-table tr').each(function() {
var hours = $(this).find('input.hours').val();
var rate = $(this).find('input.rate').val();
var dateTotal = (hours * rate);
$(this).find('input.date-total').val(dateTotal);
// total += parseInt($("input.date-total").val());
var sum = 0;
//iterate through each textboxes and add the values
$("input.date-total").each(function () {
//add only if the value is number
if (!isNaN($(this).val()) && $(this).val().length != 0) {
sum += parseFloat(this.value);
}
});
if (sum < 0) {
alert("Total can't be negative");
$('#grandtotal-new').val('');
} else {
$("#grandtotal-new").val(sum)
}
}); //END .each
return false;
}); // END click
});
$(function(){
var counter = 4;
$('a.add-row').click(function(event){
event.preventDefault();
counter++;
var newRow = jQuery('<tr><td><input type="text" value="" /></td><td><input type="text" class="hours" name="rate-0' + counter + '"/></td><td><input type="text" class="rate" name="rate-0' + counter + '"/></td><td><input type="text" class="date-total" readonly name="date-total-0' + counter + '"/></td></tr>');
$('table.hours-table').append(newRow);
});
});
</script>
The html is:
<table class="hours-table">
<tr>
<th>Item</th>
<th>Hours</th>
<th>Hourly Rate</th>
<th>Total</th>
</tr>
<tr>
<td>Base Rate:</td>
<td class="hours"><input type="number" class="hours" id="base-hours" name="hours-01" max="???" min="???" value="" /></td>
<td class="rate"><input min="0" class="rate" name="rate-01" value="200" readonly /></td>
<td class="date-total"><input type="text" class="date-total" name="date-total-0" readonly /></td>
</tr>
<tr>
<td>Second Rate:</td>
<td class="hours"><input type="number" class="hours" name="hours-02" max="???" min="???" value="" /></td>
<td class="rate"><input type="text" class="rate" name="rate-02" value="-20" readonly /></td>
<td class="date-total"><input type="text" class="date-total" name="date-total-1" readonly /></td>
</tr>
<tr>
<td>Third Rate:</td>
<td class="hours"><input type="number" class="hours" name="hours-03" max="???" min="???" value="" /></td>
<td class="rate"><input type="text" class="rate" name="rate-03" value="10" readonly /></td>
<td class="date-total"><input type="text" class="date-total" name="date-total-2" readonly/></td>
</tr>
</table>
Add New Rule<br />
<button type="button" id='calculate' class="btn btn-inverse btn- mini">Calculate</button>
The Grand total is: <input type="number" id='grandtotal-new' min="???"/>
Just validate them on blur of each .hours input as below:
DEMO
$(document).on('blur','.hours',function(){
var current=$(this);
if(!(current).is('input.hours:first'))
{
if(current.val()>$('input.hours:first').val())
current.val('');
}
});
This will check value of input on blur and clears it if it is greater than first one
UPDATE:
DEMO
parse the value before checking as below:
$(document).on('blur','.hours',function(){
var current=$(this);
if(!(current).is('input.hours:first'))
{
if(parseInt(current.val())>parseInt($('input.hours:first').val()))
current.val('');
}
});
UPDATE 2
Based on OPs comments here is the way to achieve the requirements mentioned by him.
DEMO
$(document).on('blur','.hours',function(e){
var current=$(this);
var base=$('input.hours:first');
var total=0;
var other=$('input.hours:not(:first)');
if(base.val()==="")
{
alert('Enter Base First');
current.val('');
base.focus();
e.stopPropagation();
return;
}
$.each($(other),function(index,value){
if(value.value!=="")
total+=parseInt(parseInt(value.value));
});
console.log(total);
if(!(current).is(base))
{
if(parseInt(current.val())>parseInt(base.val()))
{
current.val('');
}
else if(total>parseInt($('input.hours:first').val()))
current.val('');
}
});
add this at the beginning of your jquery script.
this will limit the other hours input to whatever is on base-hours, including newly added rows.
var baseRate = 0;
$(".hours-table").on("input","input.hours",function() {
if ($(this).attr('id') == 'base-hours'){
baseRate = $(this).val();
}else if ($(this).val() > baseRate){
$(this).val(baseRate);
}
});
and then further down below you have a syntax/logic error on your add row function. replace this line with this corrected line, and you might wanna move your counter++ after this line.
var newRow = jQuery('<tr><td><input type="text" value="" /></td><td><input type="text" class="hours" name="rate-0' + counter + '"/></td><td><input type="text" class="rate" name="rate-0' + counter + '"/></td><td><input type="text" class="date-total" readonly name="date-total-0' + counter + '"/></td></tr>');
check this jsfiddle - http://jsfiddle.net/uuzhuom9/8/

How to get values of dynamically created input fields (Json)

input fields are created via jquery depend on user input
If user type Quantity : 5 then i m created 5 input fields
for example if user give Quantity = 3 then this is how the html created dynamically using Jquery
<tr id = "tr_1">
<td><input type="text" name="cont_no1" id="cont_no1" /><td>
<td><input type="text" name="cont_size1" id="cont_size1" /><td>
<td><input type="text" name="cont_type1" id="cont_type1" /><td>
</tr>
<tr id = "tr_2">
<td><input type="text" name="cont_no2" id="cont_no1" /><td>
<td><input type="text" name="cont_size2" id="cont_size2" /><td>
<td><input type="text" name="cont_type2" id="cont_type2" /><td>
</tr>
<tr id = "tr_3">
<td><input type="text" name="cont_no3" id="cont_no3" /><td>
<td><input type="text" name="cont_size3" id="cont_size3" /><td>
<td><input type="text" name="cont_type3" id="cont_type3" /><td>
</tr>
now i need to store all this input fields values in json.
var jsonObj= jsonObj || [];
for(var i=1; i<cont_qty; i++)
{
item = {};
item ["cont_no"] = $('#cont_no'+i).val();
item ["cont_size"] = $('#cont_size'+i).val();
item ["cont_type"] = $('#cont_type'+i).val();
jsonObj.push(item);
}
i tried like this but its not working the please someone help me. ThankYou
for your refrence here is full code, var auto_tr value is aligned here(with enter) for your purpose .
$(document).ready(function(){
$( "#cont_qty" ).change(function()
{
var itemCount = 0;
$("#munna").empty();
var cont_qty = this.value;
for(var i=0 ; cont_qty>i; i++)
{
itemCount++;
// dynamically create rows in the table
var auto_tr = '<tr id="tr'+itemCount+'">
<td>
<input class="input-medium" type="text" id="cont_no'+itemCount+'" name="cont_no'+itemCount+'" value="">
</td>
<td>
<select class="input-mini" name="cont_size'+itemCount+'" id="cont_size'+itemCount+'">
<option>20</option>
<option>40</option>
<option>45</option>
</select>
</td>
<td>
<select class="input-mini" name="cont_type'+itemCount+'" id="cont_type'+itemCount+'">
<option>DV</option>
<option>HD</option>
<option>HC</option>
<option>OT</option>
<option>FR</option>
<option>HT</option>
<option>RF</option>
</select>
</td>
<td>
<select class="input-medium" name="cont_tonnage'+itemCount+'" id="cont_tonnage'+itemCount+'">
<option>24000 Kgs</option>
<option>27000 Kgs</option>
<option>30480 Kgs</option>
<option>Super Heavy Duty</option>
</select>
</td>
<td>
<input class="input-medium" type="text" id="cont_tare'+itemCount+'" name="cont_tare'+itemCount+'" value="">
</td>
<td>
<input class="input-medium" name="cont_netweight'+itemCount+'" id="cont_netweight'+itemCount+'" type="text" value="">
</td>
<td>
<input class="input-mini" name="yom'+itemCount+'" id="yom'+itemCount+'" type="text" value=""></td>
<td>
<select class="input-medium" name="cont_condition'+itemCount+'" id="cont_condition'+itemCount+'">
<option>IICL</option>
<option>ASIS</option>
<option>CARGO WORTHY</option>
</select>
</td>
</tr>';
$("#munna").append(auto_tr);
}
});
$("#getButtonValue").click(function ()
{
var jsonObj= jsonObj || [];
for(var i=1; i<cont_qty.value; i++)
{
item = {};
item ["cont_no"] = $('#cont_no'+i).val();
item ["cont_size"] = $('#cont_size'+i).val();
item ["cont_type"] = $('#cont_type'+i).val();
jsonObj.push(item);
}
alert(jsonObj[0].cont_no[1]);
});
});
did small loop mistake :)
for(var i=1; i<=cont_qty.value; i++)
{
alert(cont_qty.value);
item = {};
item ["cont_no"] = $('#cont_no'+i).val();
item ["cont_size"] = $('#cont_size'+i).val();
item ["cont_type"] = $('#cont_type'+i).val();
jsonObj.push(item);
}
in previous one i<cont_qty.value this one used now just changed as i<=cont_qty.value
so the loop ran 3 times when qty is 4. now just added <=
ThankYou for your answers friends
Make sure you call your function after you created the html via jquery.
createHtml(); // function to create the html
storeValuesToArray(); // Your function to store data to array
Also make sure you properly close your tags <tr></tr>. And put <tr> inside a <table> tag.
And make sure your cont_qty is set to a value
After you created the html and added all the fields necessary, you can catch all elements by using a selector like:
var jsonObj= jsonObj || [];
$('[name^="cont_no"]').each(function(){
var i = this.name.split('cont_no')[1];
var item = {};
item['cont_no'] = $(this).val();
item['cont_size'] = $('[name="cont_size'+i+'"]').val();
item['cont_type'] = $('[name="cont_type'+i+'"]').val();
jsonObj.push(item);
});

Categories

Resources