I am trying to change replace an html class based on value.For example if nsndatalength = 0 replace the class name with badge-success
function Awardstable(data) {
var container = document.getElementById('awardsTable');
data.forEach(function(awardsSnap) { // loop over all inventory
var Items = awardsSnap.val();
var nome = Items.Nomenclature;
var NSN = Items.NSN;
var AwardId = Items.Awardid;
var AwrdDate = Items.Awarddate;
var name = Items.Name;
// var quant = Items.Qty;
var cost = Items.Price;
var key = awardsSnap.key;
var NSNref = CatalogueDB.ref("NSNdata/" + NSN).orderByChild("NSN");
if (NSNref) {
// Attach an asynchronous callback to read the data at our posts reference
NSNref.on("value", function(nsnshot) {
if (nsnshot.val()) {
var nsndatalength = Object.keys(nsnshot.val()).length;
} else {
nsndatalength = 0;
}
console.log(nsndatalength)
console.log(nsnshot.val())
var inventoryCard = `
<tr>
<th scope="row">${NSN}</th>
<td>${nome}</td>
<td>${AwardId}</td>
<td>${AwrdDate}</td>
<td class="color-danger">${cost}</td>
<td>
<span class="badge badge-primary" id="sellerqty">${nsndatalength} Sellers</span>
</td>
<td><button type="button" class="btn btn-warning mb-1" id="buymodalbtn" data-toggle="modal" data-target="#buyModal" onclick="buyModal('${NSN}')">
Buy
</button></td>
</tr>
`;
container.innerHTML += inventoryCard;
if (nsndatalength == 0){
var buybtn = document.getElementById('buymodalbtn')
var qtymarker = document.getElementById('sellerqty')
console.log("class",buybtn,qtymarker)
document.getElementById("buymodalbtn").className = document.getElementById("buymodalbtn").className.replace
( /(?:^|\s)btn-warning(?!\S)/g , 'btn-success' )
document.getElementById("sellerqty").className = document.getElementById("sellerqty").className.replace
( /(?:^|\s)badge-primary(?!\S)/g , 'badge-success' )
}
})
} else {
nsndatalength = 0;
console.log("No Awards Available")
}
});
}
The problem is that the code is not working for all inventoryCard. This is the output of the html. The last item 0 sellers and buy button should also change color. What am I doing wrong from the code above?
We can use classList.toggle to toggle a class on/off, with the second parameter we can force it to be on/off.
Here we give the item a unique id:
<span class="badge badge-primary" id="sellerqty-${AwardId}">
then select it with:
document.getElementById(`sellerqty-${AwardId}`)
In your code it would look something like this by giving the item a unique id:
var inventoryCard = `
<tr>
<th scope="row">${NSN}</th>
<td>${nome}</td>
<td>${AwardId}</td>
<td>${AwrdDate}</td>
<td class="color-danger">${cost}</td>
<td>
<span class="badge badge-primary" id="sellerqty-${AwardId}">${nsndatalength} Sellers</span>
</td>
<td>
<button type="button" class="btn btn-warning mb-1" id="buymodalbtn" data-toggle="modal" data-target="#buyModal" onclick="buyModal('${NSN}')">Buy</button>
</td>
</tr>`;
// Add it before we call getElementById
container.innerHTML += inventoryCard;
document.getElementById(`sellerqty-${AwardId}`).classList.toggle('badge-success', nsndatalength == 0)
Related
I have a checkout table from where I obtain the values to later send as an API POST request.
I've built two separate arrays and now I need to combine them, and I'm having trouble to achieve this.
This is my code:
let orderItems = "";
let orderArray = [];
let prodsArray = [];
let datesObj = {};
let modifiersArray = [];
let comboMealsArray = [];
let modifiersObj = {};
let modifierID;
let modifierPrice;
for(var i = 0; i < jQuery(".woocommerce-table__line-item.order_item .wc-item-meta li").length; i++){//get modifier id and price from table
modifierID = jQuery(".hidden-modifier-id").eq(i).text();//modifier id is hidden from frontend but obtainable
modifierPrice = jQuery(".wc-item-meta .amount").eq(i).text();//each modifier price
let removePriceSymbols = modifierPrice.replace("€","");
let formatPrice = removePriceSymbols.replace(",", ".");
if(formatPrice === ""){
formatPrice = 0;
}
let actualModifierPrice = parseFloat(formatPrice);
modifiersObj = {[modifierID]: actualModifierPrice}; //outputs: {2971: 1}
modifiersArray.push(modifiersObj);
}
console.log(modifiersArray); // outputs: [{2971: 1}, {2972: 1.5}, {2972: 1.5}, {2971: 1}, {2972: 1.5}, 2990: 0}]
for(var i = 0; i < jQuery(".woocommerce-table__line-item.order_item").length; i++){//get order values from checkout table per row
let prodsObj = {};
let prodName = jQuery(".woocommerce-table__line-item.order_item > .product-name > a").eq(i).text();//get prodName from table cell
let prodQuant = jQuery(".woocommerce-table__line-item.order_item > .product-name > .product-quantity").eq(i).text();//get prodQuant from table cell
let prodDelivetyId = jQuery(".woocommerce-table__line-item.order_item > .product-name > #delivety_api_id_field").eq(i).text();//get delivety prod api id from table cell
let prodTotal = jQuery(".woocommerce-table__line-item.order_item > .product-total > .amount").eq(i).text();//get prodTotal from table cell
let removeQuantSymbols = prodQuant.replace(/[^0-9\.]+/g,"");
let removePriceSymbols = prodTotal.replace("€","");
let formatPrice = removePriceSymbols.replace(",", ".");
orderItems += prodName + " " + prodQuant + " " + prodTotal + "\r\n";
let actualID = parseInt(orderNumber);
let actualQuant = parseInt(removeQuantSymbols);
let actualApiID = parseInt(prodDelivetyId);
let actualPrice = parseFloat(formatPrice);
let prodTotalUni = actualPrice / actualQuant;
//prodsObj.name = prodName;
//prodsObj.id = actualID;
prodsObj.api_id = actualApiID;
prodsObj.count = actualQuant;
prodsObj.price = prodTotalUni;
prodsObj.modifiers = modifiersArray;
prodsArray.push(prodsObj);
}
orderArray.push(prodsArray);
console.log(orderArray);
This is my table chekcout and this is what my API response looks like:
{"2022-12-21":[{"api_id":2753,"count":1,"price":10.5,"modifiers":[{"2971":1},{"2972":1.5},{"2972":1.5},{"2971":1},{"2972":1.5},{"2990":0}]},{"api_id":2753,"count":1,"price":9.5,"modifiers":[{"2971":1},{"2972":1.5},{"2972":1.5},{"2971":1},{"2972":1.5},{"2990":0}]},{"api_id":2748,"count":1,"price":14.5,"modifiers":[{"2971":1},{"2972":1.5},{"2972":1.5},{"2971":1},{"2972":1.5},{"2990":0}]}]}
And I want it to look like this:
{"2022-12-21":[{"api_id":2753,"count":1,"price":10.5,"modifiers":[{"2971":1},{"2972":1.5}]},{"api_id":2753,"count":1,"price":9.5,"modifiers":[{"2972":1.5}]},{"api_id":2748,"count":1,"price":14.5,"modifiers":[{"2971":1},{"2972":1.5},{"2990":0}]}]}
I'm not quite sure how I would achieve this and I'm even having trouble explaning my problem correctly but hopefully you can understand by looking at my code/examples.
This is my table input structure:
<table class="woocommerce-table woocommerce-table--order-details shop_table order_details">
<thead>
<tr>
<th class="woocommerce-table__product-name product-name">Product</th>
<th class="woocommerce-table__product-table product-total">Total</th>
</tr>
</thead>
<tbody>
<tr class="woocommerce-table__line-item order_item">
<td class="woocommerce-table__product-name product-name">
<a>Fried Chicken</a><span id="delivety_api_id_field">2753</span> <strong class="product-quantity">× 1</strong><ul class="wc-item-meta"><li><strong class="wc-item-meta-label">Side Dishes Options:</strong> <p>Rice<span class="hidden-modifier-id">2971</span> (+<span class="woocommerce-Price-amount amount">1,00 <span class="woocommerce-Price-currencySymbol">€</span></span>)</p></li><li><strong class="wc-item-meta-label">Side Dishes Options:</strong> <p>French Fries<span class="hidden-modifier-id">2972</span> (+<span class="woocommerce-Price-amount amount">1,50 <span class="woocommerce-Price-currencySymbol">€</span></span>)</p></li></ul> </td>
<td class="woocommerce-table__product-total product-total">
<span class="woocommerce-Price-amount amount"><bdi>10,50 <span class="woocommerce-Price-currencySymbol">€</span></bdi></span> </td>
</tr>
<tr class="woocommerce-table__line-item order_item">
<td class="woocommerce-table__product-name product-name">
<a>Fried Chicken</a><span id="delivety_api_id_field">2753</span> <strong class="product-quantity">× 1</strong><ul class="wc-item-meta"><li><strong class="wc-item-meta-label">Side Dishes Options:</strong> <p>French Fries<span class="hidden-modifier-id">2972</span> (+<span class="woocommerce-Price-amount amount">1,50 <span class="woocommerce-Price-currencySymbol">€</span></span>)</p></li></ul> </td>
<td class="woocommerce-table__product-total product-total">
<span class="woocommerce-Price-amount amount"><bdi>9,50 <span class="woocommerce-Price-currencySymbol">€</span></bdi></span> </td>
</tr>
<tr class="woocommerce-table__line-item order_item">
<td class="woocommerce-table__product-name product-name">
<a>Steak</a><span id="delivety_api_id_field">2748</span> <strong class="product-quantity">× 1</strong><ul class="wc-item-meta"><li><strong class="wc-item-meta-label">Side Dishes Options:</strong> <p>Rice<span class="hidden-modifier-id">2971</span> (+<span class="woocommerce-Price-amount amount">1,00 <span class="woocommerce-Price-currencySymbol">€</span></span>)</p></li><li><strong class="wc-item-meta-label">Side Dishes Options:</strong> <p>French Fries<span class="hidden-modifier-id">2972</span> (+<span class="woocommerce-Price-amount amount">1,50 <span class="woocommerce-Price-currencySymbol">€</span></span>)</p></li><li><strong class="wc-item-meta-label">Preparation:</strong> <p>Rare<span class="hidden-modifier-id">2990</span></p></li></ul> </td>
<td class="woocommerce-table__product-total product-total">
<span class="woocommerce-Price-amount amount"><bdi>14,50 <span class="woocommerce-Price-currencySymbol">€</span></bdi></span> </td>
</tr>
</tbody>
<tfoot>
<tr>
<th scope="row">Subtotal:</th>
<td><span class="woocommerce-Price-amount amount">34,50 <span class="woocommerce-Price-currencySymbol">€</span></span></td>
</tr>
<tr>
<th scope="row">Shipping:</th>
<td>Local pickup</td>
</tr>
<tr>
<th scope="row">Payment method:</th>
<td>Multibanco</td>
</tr>
<tr>
<th scope="row">Total:</th>
<td><span class="woocommerce-Price-amount amount">34,50 <span class="woocommerce-Price-currencySymbol">€</span></span></td>
</tr>
</tfoot>
</table>
Edit after all comments
let orderItems = "";
let orderArray = [];
let prodsArray = [];
let datesObj = {};
let comboMealsArray = [];
let modifiersObj = {};
let modifierID;
let modifierPrice;
for(var i = 0; i < jQuery(".woocommerce-table__line-item.order_item").length; i++){//get order values from checkout table per row
let prodsObj = {};
let prodName = jQuery(".woocommerce-table__line-item.order_item > .product-name > a").eq(i).text();//get prodName from table cell
let prodQuant = jQuery(".woocommerce-table__line-item.order_item > .product-name > .product-quantity").eq(i).text();//get prodQuant from table cell
let prodDelivetyId = jQuery(".woocommerce-table__line-item.order_item > .product-name > #delivety_api_id_field").eq(i).text();//get delivety prod api id from table cell
let prodTotal = jQuery(".woocommerce-table__line-item.order_item > .product-total > .amount").eq(i).text();//get prodTotal from table cell
let removeQuantSymbols = prodQuant.replace(/[^0-9\.]+/g,"");
let removePriceSymbols = prodTotal.replace("€","");
let formatPrice = removePriceSymbols.replace(",", ".");
orderItems += prodName + " " + prodQuant + " " + prodTotal + "\r\n";
let modifiersArray = [];
let prodMods = jQuery(".woocommerce-table__line-item.order_item").eq(i).find("li");
for(let prodMod of prodMods) {
modifierID = jQuery(".hidden-modifier-id", prodMod).text();//modifier id is hidden from frontend but obtainable
modifierPrice = jQuery(".amount", prodMod).text();//each modifier price
let removePriceSymbols = modifierPrice.replace("€","");
let formatPrice = removePriceSymbols.replace(",", ".");
if(formatPrice === ""){
formatPrice = 0;
}
let actualModifierPrice = parseFloat(formatPrice);
modifiersObj = {[modifierID]: actualModifierPrice}; //outputs: {2971: 1}
modifiersArray.push(modifiersObj);
}
let actualID = parseInt(orderNumber);
let actualQuant = parseInt(removeQuantSymbols);
let actualApiID = parseInt(prodDelivetyId);
let actualPrice = parseFloat(formatPrice);
let prodTotalUni = actualPrice / actualQuant;
prodsObj.name = prodName;
prodsObj.id = actualID;
prodsObj.api_id = actualApiID;
prodsObj.count = actualQuant;
prodsObj.price = prodTotalUni;
prodsObj.modifiers = modifiersArray;
prodsArray.push(prodsObj);
}
orderArray.push(prodsArray);
console.log(orderArray);
I feel like you should learn a bit more about jQuery, there are things that you can do with it that really fits this situation (like searching for data in a given context). I'll maybe try to refine this even more at some point, but at least this works the way you intended it.
What I've done is create a second loop INSIDE the main loop, that iterates over each li element that represents a modifier, then jQueried the data you needed in that li element context.
I need some help in explaining to me how I can save data from dynamically added inputs to my SQL database table.
What I am doing is creating an online quote / invoice web site whereby one can create the quote and then save the data or print to pdf. (I am currently working on the "save the data" bit :-) )
So by adding the input fields (text boxes) I use a java script as per below:
(function (document) {
var
head = document.head = document.getElementsByTagName('head')[0] || document.documentElement,
elements = 'article aside audio bdi canvas data datalist details figcaption figure footer header
hgroup mark meter nav output picture progress section summary time video x'.split(' '),
elementsLength = elements.length,
elementsIndex = 0,
element;
while (elementsIndex < elementsLength) {
element = document.createElement(elements[++elementsIndex]);
}
element.innerHTML = 'x<style>' +
'article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}' +
'audio[controls],canvas,video{display:inline-block}' +
'[hidden],audio{display:none}' +
'mark{background:#FF0;color:#000}' +
'</style>';
return head.insertBefore(element.lastChild, head.firstChild);
})(document);
(function (window, ElementPrototype, ArrayPrototype, polyfill) {
function NodeList() { [polyfill] }
NodeList.prototype.length = ArrayPrototype.length;
ElementPrototype.matchesSelector = ElementPrototype.matchesSelector ||
ElementPrototype.mozMatchesSelector ||
ElementPrototype.msMatchesSelector ||
ElementPrototype.oMatchesSelector ||
ElementPrototype.webkitMatchesSelector ||
function matchesSelector(selector) {
return ArrayPrototype.indexOf.call(this.parentNode.querySelectorAll(selector), this) > -1;
};
ElementPrototype.ancestorQuerySelectorAll = ElementPrototype.ancestorQuerySelectorAll ||
ElementPrototype.mozAncestorQuerySelectorAll ||
ElementPrototype.msAncestorQuerySelectorAll ||
ElementPrototype.oAncestorQuerySelectorAll ||
ElementPrototype.webkitAncestorQuerySelectorAll ||
function ancestorQuerySelectorAll(selector) {
for (var cite = this, newNodeList = new NodeList; cite = cite.parentElement;) {
if (cite.matchesSelector(selector)) ArrayPrototype.push.call(newNodeList, cite);
}
return newNodeList;
};
ElementPrototype.ancestorQuerySelector = ElementPrototype.ancestorQuerySelector ||
ElementPrototype.mozAncestorQuerySelector ||
ElementPrototype.msAncestorQuerySelector ||
ElementPrototype.oAncestorQuerySelector ||
ElementPrototype.webkitAncestorQuerySelector ||
function ancestorQuerySelector(selector) {
return this.ancestorQuerySelectorAll(selector)[0] || null;
};
})(this, Element.prototype, Array.prototype);
function generateTableRow() {
var emptyColumn = document.createElement('tr');
emptyColumn.innerHTML = '<td><a class="cut" title="Remove Item">-</a><span contenteditable></span>
</td>' +
'<td><span contenteditable></span></td>' +
'<td><span data-prefix>₹</span><span contenteditable>0.00</span></td>' +
'<td><span contenteditable>1</span></td>' +
'<td><span data-prefix>₹</span><span>0.00</span></td>';
return emptyColumn;
}
function parseFloatHTML(element) {
return parseFloat(element.innerHTML.replace(/[^\d\.\-]+/g, '')) || 0;
}
function parsePrice(number) {
return number.toFixed(2).replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1,');
}
function updateNumber(e) {
var
activeElement = document.activeElement,
value = parseFloat(activeElement.innerHTML),
wasPrice = activeElement.innerHTML == parsePrice(parseFloatHTML(activeElement));
if (!isNaN(value) && (e.keyCode == 38 || e.keyCode == 40 || e.wheelDeltaY)) {
e.preventDefault();
value += e.keyCode == 38 ? 1 : e.keyCode == 40 ? -1 : Math.round(e.wheelDelta * 0.025);
value = Math.max(value, 0);
activeElement.innerHTML = wasPrice ? parsePrice(value) : value;
}
updateInvoice();
}
function updateInvoice() {
var total = 0;
var cells, price, total, a, i;
for (var a = document.querySelectorAll('table.inventory tbody tr'), i = 0; a[i]; ++i) {
// get inventory row cells
cells = a[i].querySelectorAll('span:last-child');
// set price as cell[2] * cell[3]
price = parseFloatHTML(cells[2]) * parseFloatHTML(cells[3]);
// add price to total
total += price;
// set row total
cells[4].innerHTML = price;
}
// get label cells
label_cells = document.querySelectorAll('table.balance th span:last-child');
tax_rate = label_cells[1].innerHTML / 100;
// get balance cells
cells = document.querySelectorAll('table.balance td:last-child span:last-child');
// set total
cells[0].innerHTML = total;
// set tax
cells[1].innerHTML = parsePrice(total * tax_rate);
// set balance and meta balance
cells[2].innerHTML = document.querySelector('table.meta tr:last-child td:last-child span:last-
child').innerHTML = parsePrice(total + parseFloatHTML(cells[1]));
var prefix = document.querySelector('#prefix').innerHTML;
for (a = document.querySelectorAll('[data-prefix]'), i = 0; a[i]; ++i) a[i].innerHTML = prefix;
for (a = document.querySelectorAll('span[data-prefix] + span'), i = 0; a[i]; ++i) if
(document.activeElement != a[i]) a[i].innerHTML = parsePrice(parseFloatHTML(a[i]));
}
function onContentLoad() {
updateInvoice();
var
input = document.querySelector('input'),
image = document.querySelector('img');
function onClick(e) {
var element = e.target.querySelector('[contenteditable]'), row;
element && e.target != document.documentElement && e.target != document.body && element.focus();
if (e.target.matchesSelector('.add')) {
document.querySelector('table.inventory tbody').appendChild(generateTableRow());
}
else if (e.target.className == 'cut') {
row = e.target.ancestorQuerySelector('tr');
row.parentNode.removeChild(row);
}
updateInvoice();
}
function onEnterCancel(e) {
e.preventDefault();
image.classList.add('hover');
}
function onLeaveCancel(e) {
e.preventDefault();
image.classList.remove('hover');
}
function onFileInput(e) {
image.classList.remove('hover');
var
reader = new FileReader(),
files = e.dataTransfer ? e.dataTransfer.files : e.target.files,
i = 0;
reader.onload = onFileLoad;
while (files[i]) reader.readAsDataURL(files[i++]);
}
function onFileLoad(e) {
var data = e.target.result;
image.src = data;
}
if (window.addEventListener) {
document.addEventListener('click', onClick);
document.addEventListener('mousewheel', updateNumber);
document.addEventListener('keydown', updateNumber);
document.addEventListener('keydown', updateInvoice);
document.addEventListener('keyup', updateInvoice);
input.addEventListener('focus', onEnterCancel);
input.addEventListener('mouseover', onEnterCancel);
input.addEventListener('dragover', onEnterCancel);
input.addEventListener('dragenter', onEnterCancel);
input.addEventListener('blur', onLeaveCancel);
input.addEventListener('dragleave', onLeaveCancel);
input.addEventListener('mouseout', onLeaveCancel);
input.addEventListener('drop', onFileInput);
input.addEventListener('change', onFileInput);
}
}
window.addEventListener && document.addEventListener('DOMContentLoaded', onContentLoad);
function serial_file() {
document.getElementById("serial").value = Date.now();
}
function un_serial_file() {
document.getElementById("serial").value = "";
}
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
today = dd + '/' + mm + '/' + yyyy;
today_form = yyyy + '-' + dd + '-' + mm + ' ';
var serial = Date.now();
function myprint() {
window.print();
}
And on my "NewQuote.aspx" Page I have this:
<div class="container-fluid">
<div style="display: inline-block; float: left;">
<asp:DropDownList runat="server" ID="drpClientSelect" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"></asp:DropDownList><br />
<br />
<asp:Label runat="server" Text="First Name" ID="lblFirstName"></asp:Label><br />
<asp:Label runat="server" Text="Last Name" ID="lblLastName"></asp:Label><br />
<asp:Label runat="server" Text="Company Name" ID="lblCompanyName"></asp:Label><br />
<asp:Label runat="server" Text="Address" ID="lblAddress"></asp:Label><br />
<asp:Label runat="server" Text="Email" ID="lblEmail"></asp:Label><br />
<asp:Label runat="server" Text="Contact Number" ID="lblContactNumber"></asp:Label><br />
<asp:Label runat="server" Text="Web Site Address" ID="lblWebsite"></asp:Label><br />
</div>
<br />
<div>
<table class="meta" id="top_data_table">
<tbody>
<tr class="" id="invoice_number_row">
<th class="bold"><span class="invoice" id="invoice">Invoice #</span></th>
<td>
<input type="text" name="fname" /></td>
</tr>
<tr id="daterow">
<th class="bold"><span class="date" id="date">Date</span></th>
<td><span>
<input type="date" id="theDate" /></span></td>
</tr>
<tr class="" id="total_block">
<th class="bold"><span class="amount" id="amount">Ammout</span></th>
<td><span id="prefix">R</span><span></span></td>
</tr>
</tbody>
</table>
</div>
</div>
<hr />
<br />
<div class="min_height">
<table class="inventory">
<thead>
<tr>
<th class="bold">
<span class="item" id="item">Item</span>
</th>
<th class="bold">
<span class="description" id="description">Description</span>
</th>
<th class="bold">
<span class="rate" id="rate">Rate</span>
</th>
<th class="bold">
<span class="quantity" id="quantity">Quantity</span>
</th>
<th class="bold">
<span class="price" id="price">Price</span>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a class="cut" title="Remove Item">-</a>
<span contenteditable="true"></span>
</td>
<td>
<span contenteditable="true"></span>
</td>
<td>
<span data-prefix="">R</span>
<span contenteditable="true">0.00</span>
</td>
<td>
<span contenteditable="true">1</span>
</td>
<td>
<span data-prefix="">R</span><span>0.00</span>
</td>
</tr>
</tbody>
</table>
<a class="add noprint" title="Add Item">+</a>
<div class="left_btn">
<button class="mah_btn" onclick="myprint()">Print</button>
<button class="mah_btn" onclick="window.location.reload()">Reset</button>
</div>
<div class="right_tax">
<table class="balance" id="balance">
<tbody>
<tr>
<th class="bold">
<span class="subtotal" id="subtotal">Subtotal</span>
</th>
<td>
<span>R</span><span>0.00</span>
</td>
</tr>
<tr>
<th class="bold">
<span class="tax" id="tax" contenteditable="true">Include VAT </span>
<span contenteditable="true">0</span>%
</th>
<td>
<span>R</span><span>0.00</span>
</td>
</tr>
<tr>
<th class="bold">
<span class="total" id="total">Total</span>
</th>
<td>
<span>R</span><span>0.00</span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
So the end results looks like this (with the CSS ofcourse :-) )
enter image description here
As you can see you can add a new row and insert some data. If you hover over the input line a "minues" sign will popup where you can delete that row. It will also automatically multiply and add the necassary fields to display total amount. All of this works great, but I now want to save it to my SQL database table. For this I have created the table and looks like this:
CREATE TABLE [dbo].[tbl_newQuotes] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Item] NVARCHAR (MAX) NULL,
[Description] NVARCHAR (MAX) NULL,
[Rate] NVARCHAR (MAX) NULL,
[Quantity] NVARCHAR (MAX) NULL,
[Price] NVARCHAR(MAX) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
And as you can guess this is where I am stuck :-( No I have saved form data before which is realtively simple by supllying the TextBox ID and values and save that to the database. But this is a complete different ball game and am not sure on how to achieve that.
I have covered most things in the question, but if you require more info please let me know.
EDIT
If there is a simpler way maybe to achieve this I am all ears :-) Maybe a tutorial on creating an invoice / quotation web forms app?
I have tried now again and can't seem to figure it out :-(
Thanks
I want you to approach it in a different way by using a GridView control.
When you click the "+" button, you save a row you have added into the table; bind the gridview taking records from the table; and display the rows including the necessary fields calculated like total amount.
There is another way by using a DataTable. Create a DataTable and save those rows to the DataTable. Then put another button called "Save" which makes those records in the DataTable saved into the Table. After saving and refreshing the screen, bring the records saved to the DataTable to display the rows on the screen.
Provided you are using jquery, it is possible to do by creating the JSON object of the inputs you added.
Create JSON object for multiple rows
Make an ajax call to pass the JSON object to web method.
Populate datatable with parsing the JSON object
Create user defined table Type in SQL for the datatable we wish to pass.
Pass datatable to Stored procedure and in SP process the data as you want.
I using this code for calculating number of times a vehicle is added. The code is not returning the correct value. I want to calculate how many times the same vehicle is selected in each row of the table.
function calculateNumberOfVehicles(vehicleId) {
var returnValue = 0;
var table = $("#selected_students");
table.find('tr').each(function(i, el) {
var counter = 0;
var rowId = $(this).attr('id');
var actualId = rowId.substr(rowId.indexOf("_") + 1).trim();
var addedVehicleId = $("#lockedVehicleId_" + actualId).text();
if (parseInt(vehicleId) == parseInt(addedVehicleId)) {
counter++
returnValue = counter;
}
});
return returnValue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody id="selected_students">
<tr id="row_5ae958a4bb2c561a10003dcc">
<td>Adam Zaffar</td>
<td>L.K.G</td>
<td>Male</td>
<td id="lockedRoute_5ae958a4bb2c561a10003dcc">Karan Nagar</td>
<td id="lockedStop_5ae958a4bb2c561a10003dcc">Lal chowk</td>
<td id="lockedVehicle_5ae958a4bb2c561a10003dcc">JK 123</td>
<td class="delete_row_dynamic"><button relation="5b962874d2ccda10ac003702" title="Delete" id="5ae958a4bb2c561a10003dcc" class="btn btn-danger table_btn btn-outline btn-sm deleteBtn"><i class="fa fa-trash"></i></button></td>
<td id="lockedRouteId_5ae958a4bb2c561a10003dcc" class="hide">5b83dc30d2ccda0b60005c0f</td>
<td id="lockedStopId_5ae958a4bb2c561a10003dcc" class="hide">b930e948-202b-697c-5615-58939cff2ac2</td>
<td id="lockedVehicleId_5ae958a4bb2c561a10003dcc" class="hide">5b962874d2ccda10ac003702</td>
<td id="lockedVehicleIdSeats_5ae958a4bb2c561a10003dcc" class="hide">3</td>
</tr>
<tr id="row_5b17cc27bb2c5633f400197c">
<td>Adnan Mir</td>
<td>L.K.G</td>
<td>Male</td>
<td id="lockedRoute_5b17cc27bb2c5633f400197c">New Jersey City</td>
<td id="lockedStop_5b17cc27bb2c5633f400197c">City Center</td>
<td id="lockedVehicle_5b17cc27bb2c5633f400197c">JK 123</td>
<td class="delete_row_dynamic"><button relation="5b962874d2ccda10ac003702" title="Delete" id="5b17cc27bb2c5633f400197c" class="btn btn-danger table_btn btn-outline btn-sm deleteBtn"><i class="fa fa-trash"></i></button></td>
<td id="lockedRouteId_5b17cc27bb2c5633f400197c" class="hide">5b7fb426d2ccda11fc005185</td>
<td id="lockedStopId_5b17cc27bb2c5633f400197c" class="hide">aa61d076-30c1-31ff-c245-968178042e46</td>
<td id="lockedVehicleId_5b17cc27bb2c5633f400197c" class="hide">5b962874d2ccda10ac003702</td>
<td id="lockedVehicleIdSeats_5b17cc27bb2c5633f400197c" class="hide">3</td>
</tr>
</tbody>
</table>
Try this
var result = calculateNumberOfVehicles('5b962874d2ccda10ac003702');
console.log(result); // This will output the number in console.
function calculateNumberOfVehicles(vehicleId) {
var returnValue = 0;
var table = $("#selected_students");
var counter = 0;
table.find('tr').each(function(i, el) {
var rowId = $(this).attr('id');
var actualId = rowId.substr(rowId.indexOf("_") + 1).trim();
var addedVehicleId = $("#lockedVehicleId_" + actualId).text();
if (parseInt(vehicleId) == parseInt(addedVehicleId)) {
counter++
returnValue = counter;
}
});
return returnValue;
}
function calculateNumberOfVehicles(vehicleId) {
var returnValue = 0;
var table = $("#selected_students");
table.find('tr').each(function (i, el) {
var rowId = $(this).attr('id');
var actualId = rowId.substr(rowId.indexOf("_") + 1).trim();
var addedVehicleId = $("#lockedVehicleId_" + actualId).text();
if (parseInt(vehicleId) == parseInt(addedVehicleId)) {
returnValue++;
}
});
return returnValue;
}
I'm trying to write a calculator using HTML5, CSS and JavaScript. I've tested my HTML and CSS with several validators, but on adding the JavaScript functions, my buttons on the calculator aren't working. Nothing is displayed on the screen and none of the functions are being called. What am I doing wrong here? Any help would be appreciated.
Thank you
Here is my HTML code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<!-- Adding link to the .css page now -->
<script type="text/javascript" src = "calculator.js"></script>
<link rel="stylesheet" href="calculator.css">
<title>Calculator Front-End</title>
</head>
<body>
<form>
<input type = "text" id = "screenid" class = "screen" name = "calcscreen" value = "0">
<p>
</p>
<table>
<tr>
<td> </td>
<td><button class = "digitbutton" id = "digit" onclick="addDisp(this)">7</button></td>
<td><button class = "digitbutton" id = "digit" onclick="addDisp(this)">8</button></td>
<td><button class = "digitbutton" id = "digit" onclick="addDisp(this)">9</button></td>
<td><button id = "add" class = "symbolbutton" onclick="addDisp(this)">+</button></td>
</tr>
<tr>
<td></td>
<td><button class = "digitbutton" id = "digit" onclick="addDisp(this)">4</button></td>
<td><button class = "digitbutton" id = "digit" onclick="addDisp(this)">5</button></td>
<td><button class = "digitbutton" id = "digit" onclick="addDisp(this)">6</button></td>
<td><button id = "sub" class = "symbolbutton" onclick="addDisp(this)">−</button></td>
</tr>
<tr>
<td></td>
<td><button class = "digitbutton" id = "digit" onclick="addDisp(this)">1</button></td>
<td><button class = "digitbutton" id = "digit" onclick="addDisp(this)">2</button></td>
<td><button class = "digitbutton" id = "digit" onclick="addDisp(this)">3</button></td>
<td><button id = "prod" class = "symbolbutton" onclick="addDisp(this)">×</button></td>
</tr>
<tr>
<td></td>
<td></td>
<td><button class = "digitbutton" id = "digit" onclick="addDisp(this)">0</button></td>
<td><button id = "result" class = "symbolbutton" onclick="doCalc(this)">=</button></td>
<td><button id = "div" class = "symbolbutton" onclick="addDisp(this)">÷</button></td>
</tr>
</table>
</form>
</body>
</html>
-------------------------------------------------------------------------
-------------------------------------------------------------------------
****And here's my calculator.js file:****
//Defining the variables and constants I need for my functions
var previousvalue = 0; //Last button pressed
var newvalue = 0; //Current button being pressed
var previousop = 'plus';
var previnputcn = 'symbolbutton' //Classname of the previous button
//Writing the function to display elements on screen
function addDisp(button)
{
//Assume if the button pressed is a digit:
if (button.classname == "digitbutton") //Suppose button pressed = 5
{
if (previnputcn == "symbolbutton") //Suppose previous button pressed was a symbol
{
newvalue = document.getElementById("digit").value; //New value becomes 5
}
else
{
newvalue = newvalue + document.getElementById("digit").value;
//Previous button pressed was a digit, so current display is appended
}
}
document.getElementById("screenid").value = document.getElementById("screenid").value + newvalue; //Print Everything on Screen
if (button.classname == "symbolbutton") //Suppose button pressed was a symbol
{
var calcResult = doCalc(previousvalue, newvalue, previousop);
if (calcResult <= 1000000 || calcResult == "ERROR")
{
newvalue = calcResult;
}
document.getElementById("screenid").value = document.getElementById("screenid").value +newvalue;
if (newvalue == "ERROR")
{
previousvalue = 0; //Re-initalize last value to 0 in case of an error
}
else
{
previousvalue = newvalue; //Re-update current value as last value to continue calculation
}
previousop = button.id; //Last operation gets id of the current operation button
}
previnputcn = button.className; //Last button classname stored for reference for future calculations
}
/*Writing the doCalc() function which handles all the calculations*/
function doCalc(newvalue, previousvalue, previousop)
{
var output = newvalue;
if (previousop == "plus")
{
output = parseInt(previousValue) + parseInt(newvalue);
}
else if (previousop == "minus")
{
output = parseInt(previousValue) - parseInt(newvalue);
}
else if (previousop == "times")
{
output = parseInt(previousValue) * parseInt(newvalue);
}
else if (previousop == "divide")
{
if (newvalue != 0)
{
output = parseInt(previousValue) / parseInt(newvalue);
output = parseInt(output);
}
else
{
output = "ERROR";
}
}
calcResult = output;
}
There are two issues with your code.
Specify the type of each button as type="button". The default type for button is "submit" which will cause the form to be submitted on clicking. Your page is getting refreshed everytime the buttons are clicked.
Most of your buttons have the same id. Id is supposed to be unique.
You are anyways passing the button element as argument to the addDisp function on click. Use it to fetch the value.
I've this HTML code:
<fieldset class="rpni-border">
<legend class="rpni-border">Model</legend>
<table id="contenedorModelos" style="" class="table table-condensed">
<tbody id="modeloBody">
<tr>
<td>
<input type="radio" value="1" id="selModelo1" name="selModelos">
</td>
<td>Harum.</td>
</tr>
<tr>
<td>
<input type="radio" value="4" id="selModelo4" name="selModelos">
</td>
<td>Pariatur ut.</td>
</tr>
<tr>
<td>
<input type="radio" value="6" id="selModelo6" name="selModelos">
</td>
<td>Tempore animi.</td>
</tr>
<tr>
<td>
<input type="radio" value="8" id="selModelo8" name="selModelos">
</td>
<td>Voluptatem.</td>
</tr>
</tbody>
</table>
</fieldset>
<fieldset class="rpni-border">
<legend class="rpni-border">Branch</legend>
<table id="contenedorMarcas" style="" class="table table-condensed">
<tbody id="marcaBody">
<tr>
<td>
<input type="radio" value="3" id="selMarca3" name="selMarcas">
</td>
<td>Ea in sequi.</td>
</tr>
<tr>
<td>
<input type="radio" value="7" id="selMarca7" name="selMarcas">
</td>
<td>Exercitationem.</td>
</tr>
<tr>
<td>
<input type="radio" value="11" id="selMarca11" name="selMarcas">
</td>
<td>Sit alias sit.</td>
</tr>
</tbody>
</table>
</fieldset>
<fieldset class="rpni-border">
<legend class="rpni-border">Manufacturer</legend>
<table id="contenedorFabricante" style="" class="table table-condensed">
<tbody id="fabricanteBody">
<tr>
<td>
<input type="checkbox" value="3">
</td>
<td>Ea in sequi.</td>
</tr>
<tr>
<td>
<input type="checkbox" value="7">
</td>
<td>Exercitationem.</td>
</tr>
<tr>
<td>
<input type="checkbox" value="11">
</td>
<td>Sit alias sit.</td>
</tr>
</tbody>
</table>
</fieldset>
<button id="create" type="button">Create</button>
<div id="ModelBranch"></div>
<button id="createM" type="button">Join Model-Branch with Manufacturer</button>
<div id="ModelBranchManufacturer"></div>
And then there is this jQuery:
$(document).ready(function () {
function modelBranchManufacturerObject(config) {
var instance = this;
// initialize class vars
instance.modelKey = config.modelKey;
instance.branchKey = config.branchKey;
instance.manufacturerKeyCollection = [];
instance.globalKey;
// globalKey = modelKey + branchKey
instance.getGlobalKey = function () {
if (!instance.globalKey) {
instance.globalKey = instance.modelKey + '-' + instance.branchKey;
}
return instance.globalKey;
}
instance.addManufacturerKeyCollection = function (manufacturerArray) {
instance.manufacturerKeyCollection = manufacturerArray;
}
}
var modelBranchManufacturerCollection = {};
function addNewRelationModelBranch(modelKey, branchKey) {
var tempModelBranchManufacturerObjectInstance = new modelBranchManufacturerObject({
modelKey: modelKey,
branchKey: branchKey
});
var globalKey = tempModelBranchManufacturerObjectInstance.getGlobalKey();
if (!modelBranchManufacturerCollection[globalKey]) {
modelBranchManufacturerCollection[globalKey] = tempModelBranchManufacturerObjectInstance;
} else {
return false;
}
return tempModelBranchManufacturerObjectInstance;
}
function addNewRelationModelBranchManufacturer(globalKey, manufacturerArray) {
if (modelBranchManufacturerCollection[globalKey]) {
modelBranchManufacturerCollection[globalKey].manufacturerKeyCollection = manufacturerArray;
} else {
return false;
}
return modelBranchManufacturerCollection;
}
var html = '<table><tbody id="branchModel"></tbody></table>';
$("#ModelBranch").html(html);
$("#create").on("click", function () {
var currModel = $("#modeloBody").find("input[type='radio']:checked").val(),
currBranch = $("#marcaBody").find("input[type='radio']:checked").val(),
ModelBranchObject, tr;
if (currModel && currBranch) {
ModelBranchObject = addNewRelationModelBranch(currModel, currBranch);
if (ModelBranchObject) {
tr = '<tr><td><input type="checkbox" value="' + ModelBranchObject.globalKey + '" /></td>';
tr += '<td>' + ModelBranchObject.modelKey + '-' + ModelBranchObject.branchKey + '</td></tr>';
$("#branchModel").append(tr);
}
}
});
var htmlManufacturer = '<table><tbody id="branchModelManufacturer"></tbody></table>';
$("#ModelBranchManufacturer").html(htmlManufacturer);
$("#createM").on("click", function () {
var checkedModelBranch = $("#branchModelManufacturer").find("input[type='checkbox']:checked"),
checkedManufacturers = $("#fabricanteBody").find("input[type='checkbox']:checked"),
manufacturerColl = [],
trManufacturer,
ModelBranchManufacturerObject;
for (var j = 0; j < checkedManufacturers.length; j++) {
manufacturerColl.push(checkedManufacturers[j].value);
}
console.log(manufacturerColl);
for (var i = 0; i < checkedModelBranch.length; i++) {
ModelBranchManufacturerObject = addNewRelationModelBranchManufacturer(checkedModelBranch[i].value, manufacturerColl);
console.log(ModelBranchManufacturerObject);
if (ModelBranchManufacturerObject) {
trManufacturer = '<tr><td><input type="checkbox" value="' + ModelBranchManufacturerObject.globalKey + '" /></td>';
trManufacturer += '<td>' + ModelBranchObject.modelKey + '-' + ModelBranchObject.branchKey;
for (var k = 0; k < ModelBranchObject.manufacturerKeyCollection.length; k++) {
trManufacturer += ModelBranchObject.manufacturerKeyCollection[k] + '<br/>';
}
trManufacturer += '</td></tr>';
$("#branchModelManufacturer").append(trManufacturer);
}
console.log(trManufacturer);
}
});
});
What this code does is allow to pick a model and a branch and create a non repeated pairs between them and also show the results on #modelBranch div. Also allow, I think if I'm not doing something wrong, to pick one|many choices from the results in the previous step (those on #modelBranch) and one|many Manufacturers and again create a non repeated pairs between them but in this case I can not show the results on #ModelBranchManufacturer as I should do so something is not working on my code and I was not able to find where I'm failing so certainly I need some help or advice from you. For clear a bit how the process is take a look at the following example:
Pick Model1/Branch1 and click on "Create Model/Branck Pair", this will generate a pair Model1-Branch1 as image below shows.
Pick Model1/Branch2 and click on "Create Model/Branck Pair", this will generate a pair Model1-Branch2 as image below shows.
Pick Model1/Branch1 and click on "Create Model/Branck Pair", nothing will happen since this pair was added on the (1) step and this is the right behavior to follow meaning do not allow repeated pairs
Now taking the example above you should have a table like this:
checkbox Model1-Branch1
checkbox Model1-Branch2
Following with the logic now:
Pick Model1/Branch1 and Model1/Branch2 pairs and from the Manufacturers table pick Manufacturer1 and click on "Create Model/Branck-Manufacturer Pair", this should generate something like this below:
Mark to Delete | Model/Branch | Manufacturer
----------------------------------------------------
checkbox | Model1-Branch1 | Manufacturer1
checkbox | Model1-Branch2 | Manufacturer1
Pick Model1/Branch1 and Model1/Branch2 pairs and from the Manufacturers table pick Manufacturer1 and Manufacturer2 and Manufacturer3 and click on "Create Model/Branck-Manufacturer Pair", this should generate something like this below:
Mark to Delete | Model/Branch | Manufacturer
----------------------------------------------------
checkbox | Model1-Branch1 | Manufacturer1
| | Manufacturer2
| | Manufacturer3
----------------------------------------------------
checkbox | Model1-Branch2 | Manufacturer1
| | Manufacturer2
| | Manufacturer3
Pick Model1/Branch1 and Model1/Branch2 pairs and from the Manufacturers table pick Manufacturer1 and click on "Create Model/Branck-Manufacturer Pair", nothing should happen since this pair was added on the (1) step and this is the right behavior to follow meaning do not allow repeated pairs
So, why the results from #createM on click event are not show in #ModelBranchManufacturer? Where I'm making something wrong in my code? I made this Fiddle for testing purpose
Ok, after some hours of coffee and a lot of headaches I got the solution and it's working. Maybe this code is a bit different from the main on the post since I made some changes but the idea still:
function modelBranchManufacturerObject(config) {
var instance = this;
// initialize class vars
instance.modelKey = config.modelKey;
instance.branchKey = config.branchKey;
instance.manufacturerCollection = [];
instance.modelName = config.modelName || 'Sin nombre asignado';
instance.branchName = config.branchName || 'Sin nombre asignado';
instance.globalKey;
// globalKey = modelKey + branchKey
instance.getGlobalKey = function () {
if (!instance.globalKey) {
instance.globalKey = instance.modelKey + '-' + instance.branchKey;
}
return instance.globalKey;
}
}
var modelBranchManufacturerCollection = {};
function addNewRelationModelBranch(modelKey, branchKey, modelName, branchName) {
var tempModelBranchManufacturerObjectInstance = new modelBranchManufacturerObject({
modelKey: modelKey,
branchKey: branchKey,
modelName: modelName,
branchName: branchName
});
var globalKey = tempModelBranchManufacturerObjectInstance.getGlobalKey();
if (!modelBranchManufacturerCollection[globalKey]) {
modelBranchManufacturerCollection[globalKey] = tempModelBranchManufacturerObjectInstance;
} else {
return false;
}
return tempModelBranchManufacturerObjectInstance;
}
function addNewRelationModelBranchManufacturer(globalKey, manufacturerArray) {
var manufacturerCollection = modelBranchManufacturerObject.manufacturerCollection;
if (modelBranchManufacturerCollection[globalKey]) {
if (manufacturerCollection !== manufacturerArray) {
modelBranchManufacturerCollection[globalKey].manufacturerKeyCollection = manufacturerArray;
return modelBranchManufacturerCollection[globalKey];
}
} else {
return false;
}
}
$("#btnCrearParMarcaModelo").on("click", function () {
var currModel = $("#modeloBody").find("input[type='radio']:checked").val(),
currBranch = $("#marcaBody").find("input[type='radio']:checked").val(),
currModelName = $("#modeloBody").find("input[type='radio']:checked").parent().next('td').text(),
currBranchName = $("#marcaBody").find("input[type='radio']:checked").parent().next('td').text(),
ModelBranchObject, tr;
if (currModel && currBranch) {
ModelBranchObject = addNewRelationModelBranch(currModel, currBranch, currModelName, currBranchName);
if (ModelBranchObject) {
tr = '<tr><td><input type="checkbox" value="' + ModelBranchObject.globalKey + '" /></td>';
tr += '<td>' + ModelBranchObject.modelName + '-' + ModelBranchObject.branchName + '</td><td id="' + ModelBranchObject.globalKey + '"></td></tr>';
$("#parMarcaModeloFabricanteBody").append(tr);
}
}
$("#parMarcaModeloFabricante").show();
});
$("#btnAgregarSelFabricante").on("click", function () {
console.log("d");
var checkedModelBranch = $("#parMarcaModeloFabricanteBody").find("input[type='checkbox']:checked"),
checkedManufacturers = $("#selFabricanteBody").find("input[type='checkbox']:checked"),
manufacturerColl = [],
modelBranchManufacturerCollection;
var j = checkedManufacturers.length, item;
while (j--) {
item = checkedManufacturers[j];
if (item.type && item.type == 'checkbox' && item.checked) {
manufacturerColl.push({
id: item.value,
name: item.parentNode.nextSibling.innerHTML
});
}
}
for (var i = 0; i < checkedModelBranch.length; i++) {
modelBranchManufacturerCollection = addNewRelationModelBranchManufacturer(checkedModelBranch[i].value, manufacturerColl);
if (modelBranchManufacturerCollection) {
//$("#parMarcaModeloFabricanteBody td#" + checkedModelBranch[i].value).siblings().attr("rowspan", modelBranchManufacturerCollection.manufacturerKeyCollection.length);
for (var k = 0; k < modelBranchManufacturerCollection.manufacturerKeyCollection.length; k++) {
$("#parMarcaModeloFabricanteBody td#" + checkedModelBranch[i].value).append((modelBranchManufacturerCollection.manufacturerKeyCollection)[k].name + '<br/>');
}
}
}
});