Comparing readonly value with a value entered by a user - javascript

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)

Related

How to get values to the outside from three functions and update them in real time?

I have a table which lets users to add number of participants for an event. in it I used input type number field to get number of participants. then I calculate how much fee they have to pay for each passenger type. I have 3 passenger types.
My table looks like this,
I use keyup mouseup bind to get the input value by user and multiplied it with fee for one participant.
var totalAdults;
jQuery("#number_adults").bind('keyup mouseup', function () {
var numOfAdults = jQuery("#number_adults").val();
totalAdults = numOfAdults * adultFee;
});
I have 3 of above functions to calculate and real time display how much fee that they have to pay in each passenger type.
Now I need to get the total sum of all three passenger type fees and display/update it in real time to the user, at the end of my table.
I tried making each passenger type total value global and calculating it's sum, but I get an error saying missing semicolon error linked to this MDN article
I'm stuck here. how can I get total value on all three passenger types outside their respective functions and display that value correctly in real time? (when they update number of passengers, total for passenger type is changing, I need to change final total accordingly). please help
Update:
this is the html table that I used. this get repeated another two times for other two passenger types.
var adultFee = 150;
var finalTotal = 0;
jQuery("#number_adults").bind('keyup mouseup', function() {
var numOfAdults = jQuery("#number_adults").val();
totalAdults = numOfAdults * adultFee;
jQuery("#adult_amount").html(totalAdults);
// console.log(totalAdults);
finalTotal = finalTotal + totalAdults;
console.log(finalTotal);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr>
<td style="font-weight: 600;">Adult</td>
<td id="adult_price" name="adult_price">150.00</td>
<td>
<input id="number_adults" max="3" min="1" name="number_adults" type="number" value="0" class="form-control">
</td>
<td name="amount">
<p id="adult_amount"></p>
</td>
</tr>
This is how I tried to get the final total, it doesn't display any result
jQuery(document).on('change', '#adult_amount', function() {
finalTotal = finalTotal+totalAdults;
alert(finalTotal);
});
I made a working example for you.
$('.inputs').each(function(){
$(this).on('change keyup', function(){
let sumTotal = 0;
$('.inputs').each(function(){
sumTotal += $(this).val() * +$(this).parent().next().data('price');
});
$('.total').text(`${sumTotal} $`);
});
});
td:nth-child(3),
th:nth-child(3){
text-align:center;
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-12">
<table class="table table-hover">
<thead>
<tr>
<th></th>
<th>QTY</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>Child</td>
<td><input type="number" class="inputs form-control" value="0" min="0" max="999"></td>
<td class="price" data-price="150">150 $</td>
</tr>
<tr>
<td>Adult</td>
<td><input type="number" class="inputs form-control" value="0" min="0" max="999"></td>
<td class="price" data-price="200">200 $</td>
</tr>
<tr>
<td>Adult Plus</td>
<td><input type="number" class="inputs form-control" value="0" min="0" max="999"></td>
<td class="price" data-price="250">250 $</td>
</tr>
<tr>
<td>Total - </td>
<td></td>
<td class="total">0.00 $</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
(https://codepen.io/bichiko/pen/JQWomy)
Here is a solution which should do what you need.
Compared to your code, the key changes are:
Use classes instead of IDs to identify the elements within each row. This means you can handle changes to all your fields using the same event handling code. I've given all your quantity fields the .qty class, and then bound the event to that class, so all elements with that class will run the same function.
Within the function, I've stripped out all direct references to fields - instead, to get the price field, and the total field for the relevant type, the code uses the positions of the fields relative to each other in the page, it uses the .parent(), .next(), and .prev() functions to find the total and amount fields which are within the same table row as the altered quantity field (which will always be this inside the event handler), so that it does the calculations on the right fields.
To calculate the final overall total, I've defined a separate function. Again this uses a class selector to identify all the "amount" fields, and add each of those values together to get the total. Since this function is triggered at the end of the event handler, it will always update the grand total whenever one of the quantities is updated.
Other minor changes:
use .on() instead of the deprecated .bind()
jQuery(".qty").on('keyup mouseup', function() {
var tdElement = jQuery(this).parent();
var qty = parseInt(this.value);
var fee = parseFloat(tdElement.prev(".price").text());
var typeTotal = qty * fee;
tdElement.next(".amount").html(typeTotal);
calcFinalTotal();
});
function calcFinalTotal()
{
var finalTotal = 0;
$(".amount").each(function() {
finalTotal += parseFloat($(this).text());
});
$("#total").text(finalTotal);
}
td, th
{
border: solid 1px #cccccc;
padding: 5px;
text-align:left;
}
table {
border-collapse: collapse;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>Passenger Type</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
<tr>
<th>Adult</th>
<td class="price">150.00</td>
<td>
<input max="3" min="1" name="number_adults" type="number" value="0" class="form-control qty">
</td>
<td class="amount">0
</td>
</tr>
<tr>
<th>Type 2</th>
<td class="price" id="type3_price">200.00</td>
<td>
<input max="3" min="1" name="number_type" type="number" value="0" class="form-control qty">
</td>
<td class="amount">0
</td>
</tr>
<tr>
<th>Type 3</th>
<td class="price" id="type3_price">200.00</td>
<td>
<input max="3" min="1" name="number_type" type="number" value="0" class="form-control qty">
</td>
<td class="amount">0
</td>
</tr>
<tr>
<th colspan="3">Grand Total</th>
<td id="total"></td>
</tr>
</table>
You can simply loop on every rows on the table and calculate the total sum and also the individual. Here i done by the dynamic method. if the total of each passenger is inserted in a unique input, then you can access from that input. Otherwise please follow the method
$(document).on('keyup mouseup','.qty', function() {
calculate();
});
function calculate(){
var finalTotal = 0;
var old = 0;
var mature = 0;
var adult = 0;
$('.qty').each(function(key,value){
$qty = $(this).val();
$type = $(this).attr('data-type');
$amount = $(this).parent().siblings('.adult_price').html();
$total = Number($qty) * parseFloat($amount);
$(this).parent().siblings('.amount').html($total);
finalTotal += $total;
if($type == 'adult')
adult += parseFloat($total);
else if($type == 'mature')
mature += parseFloat($total);
else if($type == 'old')
old += parseFloat($total);
});
$('.grandTotal').html(finalTotal);
// console.log('Adult',adult);
// console.log('Mature',mature);
// console.log('Old',old);
}
table {
border-collapse: collapse;
width: 80%;
}
th, td {
text-align: left;
padding: 8px;
}
tr:nth-child(even){background-color: #f2f2f2}
th {
background-color: #4CAF50;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Passenger Types</th>
<th>Amount</th>
<th>Qty</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td><b>Adult</b></td>
<td class="adult_price" name="adult_price">150.00</td>
<td>
<input max="3" min="1" name="number_adults" type="number" value="0" class="form-control qty" data-type="adult">
</td>
<td name="amount" class='amount'></td>
</tr>
<tr>
<td><b>Mature</b></td>
<td class="adult_price" name="adult_price">200.50</td>
<td>
<input max="3" min="1" name="number_adults" type="number" value="0" class="form-control qty" data-type="mature">
</td>
<td name="amount" class='amount'></td>
</tr>
<tr>
<td><b>Old</b></td>
<td class="adult_price" name="adult_price">150.00</td>
<td>
<input max="3" min="1" name="number_adults" type="number" value="0" class="form-control qty" data-type="old">
</td>
<td name="amount" class='amount'></td>
</tr>
<tr>
<td colspan="3"><b>Grand Total</b></td>
<td class='grandTotal'>100</td>
</tr>
</tbody>
</table>
jQuery is very flexible use class instead of id. If you use inputs, selects, etc you should delegate the input or change event to them.
$('input').on('input', function() {...
input event will trigger as soon as user types or selects on or to an input tag. change event will trigger when a user types or selects on or to an input and then clicks (unfocus or blur event) elsewhere.
The HTML is slightly modified for consistency. Note that there are 2 extra inputs per <tr>.
When using input inside tables you can traverse the DOM by first referencing the imputed/changed/clicked tag as $(this) then climb up to the parent <td> and from there either go to the next <td> using .next() or go to the previous <td> using .prev(). Once you get to a neighboring <td> use .find() to get the input within. When extracting a number from an input it is normally a string but with jQuery method .val() it should extract input value as a number automatically. Details commented in demo.
/*
//A - Any tag with the class of .qty that the user inputs data into triggers a function
//B - Get the value of the imputed .qty (ie $(this))
//C - reference $(this) parent <td> go to the next <td> then find a tag with the class .price and get its value
//D - reference $(this) parent <td> go to the previous <td> then find a tag with the class of .total then set its value to the product of qty and price and fix it with hundredths (.00 suffix)
//E - Declare an empty array
//F - Get the value of each .total, convert it into a number then push the number into the empty array
//G - Use .reduce() to get the sum of all values within the array then fix it with hundredths (.00 suffix) and set it as the value of .grand
*/
$('.qty').on('input', function() { //A
var qty = $(this).val(); //B
var price = $(this).parent().prev('td').find('.price').val(); //C
$(this).parent().next('td').find('.total').val((qty * price).toFixed(2)); //D
var totals = []; //E
$('.total').each(function() {
totals.push(Number($(this).val()));
}); //F
$('.grand').val(totals.reduce((sum, cur) => sum + cur).toFixed(2)); //G
});
table {
table-layout: fixed;
}
td {
width: 6ch
}
[readonly] {
border: 0;
width: 6ch;
text-align: right
}
[type=number] {
text-align: right
}
<table>
<tr>
<td style="font-weight: 600;">Adult</td>
<td><input class="price" name='price' value='150.00' readonly></td>
<td>
<input class="qty" name="qty" min="0" max="3" type="number" value="0" class="form-control">
</td>
<td>
<input class="total" name='total' readonly>
</td>
</tr>
<tr>
<td style="font-weight: 600;">Senior</td>
<td><input class="price" name='price' value='100.00' readonly></td>
<td>
<input class="qty" name="qty" min="0" max="3" type="number" value="0" class="form-control">
</td>
<td>
<input class="total" name='total' readonly>
</td>
</tr>
<tr>
<td style="font-weight: 600;">Child</td>
<td><input class="price" name='price' value='75.00' readonly></td>
<td>
<input class="qty" name="qty" min="0" max="3" type="number" value="0">
</td>
<td>
<input class="total" name='total' readonly>
</td>
</tr>
<tr>
<td colspan='3' style='text-align:right;'>Total</td>
<td><input class='grand' name='grand' value='0' readonly></td>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This is axample of yours problem, try using object
var data = {a:0, b:0, c: 0}
function one (){
data.a = data.a + 10
console.log(data.a)
total()
}
function two (){
data.b = data.b + 10
total()
console.log(data.b)
}
function three () {
data.c = data.c + 30
total()
console.log(data.c)
}
function total () {
var totaly = data.a + data.b + data.c
console.log('Total input :', totaly)
}
<button onclick="one()"> get A </button>
<button onclick="two()"> get B</button>
<button onclick="three()"> get C </button>

How to access HTML array object in javascript?

sorry for asking simple question. I am really a beginner in Javascript. I need to access my HTML array form object in my javascript, but I don't know how to do it.
The goal is to trigger the alert in javascript so the browser will display message according to the condition in javascript. Here is my code :
checkScore = function()
{
//I don't know how to access array in HTML Form, so I just pretend it like this :
var student = document.getElementByName('row[i][student]').value;
var math = document.getElementByName('row[i][math]').value;
var physics = document.getElementByName('row[i][physics]').value;
if (parseInt(math) >= 80 ) {
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics) >= 80 ){
alert(student + " ,You are good at physics");
}
student_score.row[i][otherinfo].focus();
student_score.row[i][otherinfo].select();
}
<h2>HTML Forms</h2>
<form name="student_score" action="/action_page.php">
<table border=1>
<thead>
<td>Student</td>
<td>Math Score</td>
<td>Physics Score</td>
<td>Other info</td>
</thead>
<tbody>
<tr>
<td><input type="text" name="row[1][student]"></td>
<td><input type="number" name="row[1][math]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="number" name="row[1][physics]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="text" name="row[1][otherinfo]"></td>
</tr>
<tr>
<td><input type="text" name="row[2][student]"></td>
<td><input type="number" name="row[2][math]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="number" name="row[2][physics]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="text" name="row[2][otherinfo]"></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>
</tbody>
</table>
</form>
<p>If you click the "Submit" button, it will save the data.</p>
We are going to leverage few things here to streamline this.
The first is Event Listeners, this removes all javascript from your HTML. It also keeps it more dynamic and easier to refactor if the table ends up having rows added to it via javascript.
Next is parentNode, which we use to find the tr that enclosed the element that was clicked;
Then we use querySelectorAll with an attribute selector to get our target fields from the tr above.
/*This does the work*/
function checkScore(event) {
//Get the element that triggered the blur
var element = event.target;
//Get our ancestor row (the parent of the parent);
var row = element.parentNode.parentNode;
//Use an attribute selector to get our infor from the row
var student = row.querySelector("[name*='[student]']").value;
var math = row.querySelector("[name*='[math]']").value;
var physics = row.querySelector("[name*='[physics]']").value;
var otherField = row.querySelector("[name*='[otherinfo]']");
if (parseInt(math, 10) >= 80) {
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics, 10) >= 80) {
alert(student + " ,You are good at physics");
}
otherField.focus();
otherField.select();
}
/*Wire Up the event listener*/
var targetElements = document.querySelectorAll("input[name*='math'], input[name*='physics']");
for (var i = 0; i < targetElements.length; i++) {
targetElements[i].addEventListener("blur", checkScore);
}
<h2>HTML Forms</h2>
<form name="student_score" action="/action_page.php">
<table border=1>
<thead>
<tr>
<td>Student</td>
<td>Math Score</td>
<td>Physics Score</td>
<td>Other info</td>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="row[1][student]" class='student'></td>
<td><input type="number" name="row[1][math]" min="0" max="100"></td>
<td><input type="number" name="row[1][physics]" min="0" max="100"></td>
<td><input type="text" name="row[1][otherinfo]"></td>
</tr>
<tr>
<td><input type="text" name="row1[2][student]"></td>
<td><input type="number" name="row[2][math]" min="0" max="100"></td>
<td><input type="number" name="row[2][physics]" min="0" max="100"></td>
<td><input type="text" name="row[2][otherinfo]"></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>
</tbody>
</table>
</form>
Well, it follows your line of code exactly as it is (because you said you do not want to change the code too much).
<h2>HTML Forms</h2>
<form name="student_score" action="/action_page.php">
<table border=1>
<thead>
<td>Student</td>
<td>Math Score</td>
<td>Physics Score</td>
<td>Other info</td>
</thead>
<tbody>
<tr>
<td><input type="text" name="row[1][student]"></td>
<td><input type="number" name="row[1][math]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="number" name="row[1][physics]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="text" name="row[1][otherinfo]"></td>
</tr>
<tr>
<td><input type="text" name="row1[2][student]"></td>
<td><input type="number" name="row[2][math]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="number" name="row[2][physics]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="text" name="row[2][otherinfo]"></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>
</tbody>
</table>
</form>
JavaScript [Edited again using part of the #Jon P code, the query selector is realy more dynamic, and the value of the "other" field you requested is commented out]
//pass element to function, in html, only add [this] in parenteses
checkScore = function (element) {
//Get our ancestor row (the parent of the parent);
var row = element.parentNode.parentNode;
//Use an attribute selector to get our infor from the row
var student = row.querySelector("[name*='[student]']").value;
var math = row.querySelector("[name*='[math]']").value;
var physics = row.querySelector("[name*='[physics]']").value;
var other = row.querySelector("[name*='[otherinfo]']");
if (parseInt(math) >= 80) {
//other.value = student + " ,You are good at mathematic";
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics) >= 80) {
//other.value = student + " ,You are good at physics";
alert(student + " ,You are good at physics");
}
otherField.focus();
otherField.select();
}
Tested :), and sorry about my english!
Try that, haven't tested it
var form = document.getElementsByName("student_score")[0];
var students = form.getElementsByTagName("tr");
for(var i = 0; i < students.length; i++){
var student = students[i].childnodes[0].value;
var math = students[i].childnodes[1].value;
var physics = students[i].childnodes[2].value;
if (parseInt(math) >= 80 ) {
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics) >= 80 ){
alert(student + " ,You are good at physics");
}
}

Adding to a value declared in another function

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/

how to change value of one input text field (in one html table) based on a specific value of another input text field (present in another html table)

I have one html table which has one row. This row has two TDs which hold their own tables within them (Each having 10 rows with 10 input fields). I want to change value of another respective text field based on value change in first field onblur().
First field-. It takes value from an Array of size 10
<tr>
<td valign="top">
<table width="85%" border="0" cellpadding="2" cellspacing="1" class="inputTable">
<tr>
<td width="60%">
<table width="60%" border="0" cellpadding="0" cellspacing="1">
<c:set var="input1" value="${someForm.value1}"></c:set>
<c:forTokens items="0,1,2,3,4,5,6,7,8,9" delims="," var="count">
<tr>
<td><input id="field1" name="field1" type="text" value="<c:out value="${input1[count]}" />" onblur="setText2(this)" maxlength="20" size="15">
</td>
</tr>
</c:forTokens>
</table>
</td>
</tr>
</table>
</td>
Second field. This requires value chnage on run when respective value changes for above 10 fields
<td valign="top">
<table width="85%" border="0" cellpadding="2" cellspacing="1" class="inputTable">
<tr>
<td width="60%">
<table width="60%" border="0" cellpadding="0" cellspacing="1">
<c:forTokens items="0,1,2,3,4,5,6,7,8,9" delims="," var="count">
<tr>
<td><input id="field2" name="field2" type="text" value="" />" readonly class="readonly" maxlength="1" size="1">
</td>
</tr>
</c:forTokens>
</table>
</td>
</tr>
</table>
</td>
</tr>
Javascript:
<script>
function setText2(element) {
if(element.value)
{
document.getElementById("field2").value = element.value;
}else{
document.getElementById("indicator").value = "";
}
}
</script>
This is running fine. But problem is I am able to identified which field is being changed through this but unable to get reference of target field. This changes value of second fields but always in first row of second table.
Please help me to run this so that if a field changes of table1 , then the repective (same serial) field of table 2 should change. I cant change the table structure due to some project limitations.
getElementById() is selecting the first element with id="field2". You shouldn't give the same id to multiple elements. Try changing the id to correspond to the count, then in your javascript function you can get the field2 input that corresponds to the count of the blurred input.
Replace your field1 code with this:
<input id="field1_${count}" name="field1" type="text" value="${input1[count]}"
onblur="setText2(this)" maxlength="20" size="15"/>
Replace your field2 code with this:
<input id="field2_${count}" name="field2" type="text" value=""
readonly="readonly" class="readonly" maxlength="1" size="1">
Then change your javascript function:
function setText2(element) {
if(element.value)
{
var changedId = element.id;
var elementNumber = changedId.substring(changedId.indexOf('_') + 1);
document.getElementById("field2_" + elementNumber).value = element.value;
}else{
document.getElementById("indicator").value = "";
}
}
As answered by Tap, assign distinct id for each field (of array). The only thing I want to add is, we should use c:out while assigning number to id as given below (otherwise id will not have numbers as being expected rather it will assign string as "field1_${count}" ):
Use:
<input id="<c:out value="field1_${count}" />" name="field1" type="text" value="<c:out value="${input1[count]}" />" onblur="setText2(this)" maxlength="20" size="15"/>
This runs well!! ;)
I am happy; this solved my big problem without affecting structure of the code...
Thanks a lot again Tap, for your suggestion. :)

Accessing Element From ngRepeat

How can I access a given record inside an ngRepeat loop from the controller, ultimately for form validate?
I have the following form which can have records dynamically added/removed by the user:
<table class="table table-condensed span12" id="tableParticipants">
<!-- snip -->
<tbody>
<tr ng-repeat="person in people">
<td><input type="text" pattern="[0-9]*" data-provide="typeahead" placeholder="8675309" ng-model="person.empid"></td>
<td><input type="text" data-provide="typeahead" placeholder="Firstname Lastname" ng-model="person.name"></td>
<td><input type="text" placeholder="Title" ng-model="person.title"></td>
<td style="text-align: center"><i class="icon-remove" ng-click="removeParticipant()"></i></td>
</tr>
</tbody>
</table>
On submitting the form I need to make sure that the employee IDs are valid, else I will get a database error. So, when I work through the loop:
$scope.people.forEach(function(element, index, array)
{
if ($element['empid'] == BAD)
{
// set corredponding ngRepeat row to error
}
}
How can I access that given row for the particular record?
You should be able to do something like the following. Add a css class name to the array item and/or an error message. The rest should be handled by Angular which will update. You have options of show/hiding a message, adding a class, etc.
<tr ng-repeat="person in people" ng-class="person.error">
<td><input type="text" pattern="[0-9]*" data-provide="typeahead" placeholder="8675309" ng-model="person.empid"></td>
<td><input type="text" data-provide="typeahead" placeholder="Firstname Lastname" ng-model="person.name"></td>
<td><input type="text" placeholder="Title" ng-model="person.title"></td>
<td style="text-align: center"><i class="icon-remove" ng-click="removeParticipant()"></i> <span>{{person.errorMessage}}</td>
</tr>
if ($element['empid'] == BAD)
{
$element['errorMessage'] = 'Invalid Id'; // could bind or show a span/depends.
$element['error'] = 'error'; // set to whatever class you want to use.
}

Categories

Resources