I create my personal project, and I called this system as ordering system I used laravel for this and the front end javascript and jquery.
I have question
Question:
I used the append function of jquery to transfer value to other side. so i append input type number which the value automatically equal to 1
The question if I increment the value of input type number how the price double if i increase the value of number?
Example of my output
My Front end Codes:
var tbody = $('#myTable').children('tbody');
//Then if no tbody just select your table
var table = tbody.length ? tbody : $('#myTable');
//my logic to increment quantity but not working.
$("#qty_change").bind('keyup mouseup', function () {
alert("changed");
});
//function for getting the data from search product by clicking to the table row
$("tr#productClicked").click(function () {
//to get the price in tr
var price = $(this).closest("tr").find(".menu_price").text();
//to get the menu in tr
var menu_name = $(this).closest("tr").find(".menu_name").text();
//row count
var rowCount = $('table#myTable tr:last').index() + 1;
//append input to quantity the value is 1
var input = '<input type="number" name="qty_number" class="form-control" value="1" id="qty_change" />';
//Item must be editable
var contenteditable = 'contenteditable=true';
table.append('<tr><td>'+rowCount+'</td><td class="total">'+input+'</td><td '+contenteditable+'>'+menu_name+'</td><td>'+price+'</td><td>'+price+'</td></tr>');
});
Html Table:
<table class="table table-hover" id="myTable">
<thead>
<tr style="font-size: 14px; ">
<th scope="col">#</th>
<th scope="col">Qty</th>
<th scope="col">Item</th>
<th scope="col" style="text-align: right">Cost</th>
<th scope="col" style="text-align: right">Total</th>
</tr>
</thead>
<tbody style="font-size:14px;">
<tr>
{{-- <td>1</td>
<td>x 2</td>
<td contenteditable='true'>Feast Chicken</td>
<td align="right">$10.00</td>
<td align="right">$20.00</td> --}}
</tr>
</tbody>
</table>
New update:
$('.amount > input[type="number"]').on('input', updateTotal);
function updateTotal(e){
var value = e.target.value;
// Don't do anything if value is not valid
// else you will see NaN in result.
if (!value || value < 0)
return;
var $parentRow = $(e.target).parent().parent();
var $siblingTotal = $parentRow.find('.total');
var $siblingCost = $parentRow.find('.cost');
var cost = $siblingCost.text();
// parseInt and parseFloat because
// `value` and `cost` are strings.
value = parseInt(value);
cost = parseFloat(cost);
$siblingTotal.text(value * cost);
}
$("tr#productClicked").click(function () {
swal({
title: "Are you sure?",
text: "Once you will add it will automatically send to the cart",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
swal("Poof! Your imaginary file has been deleted!", {
icon: "success",
});
swal("Menu Added", "You clicked the button!", "success");
//to get the price in tr
var price = $(this).closest("tr").find(".menu_price").text();
//to get the menu in tr
var menu_name = $(this).closest("tr").find(".menu_name").text();
//row count
var rowCount = $('table#myTable tr:last').index() + 1;
//append input to quantity the value is 1
var input = '<input type="number" value="1">';
//Item must be editable
var contenteditable = 'contenteditable=true';
table.append('<tr><td>'+rowCount+'</td><td class="amount">'+input+'</td><td '+contenteditable+'>'+menu_name+'</td><td class="cost">'+price+'</td><td class="total">'+price+'</td></tr>');
} else {
swal("Cancelled");
}
});
});
Listen for "input" event using jQuery's .on.
(Please note that "input" event has nothing to do with jQuery, it's a native JavaScript thing.)
This is a sample code, because the code you provided is not complete. But you should be able to get the concept:
Usual code sample
$('.amount > input[type="number"]').on('input', updateTotal);
function updateTotal(e){
var amount = parseInt(e.target.value);
if (!amount || amount < 0)
return;
var $parentRow = $(e.target).parent().parent();
var cost = parseFloat($parentRow.find('.cost').text());
var total = (cost * amount).toFixed(2);
$parentRow.find('.total').text(total);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Input</th>
<th>Cost per item</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td class="amount"><input type="number" value="1"></td>
<td class="cost">27</td>
<td class="total">27</td>
</tr>
<tr>
<td class="amount"><input type="number" value="1"></td>
<td class="cost">14.50</td>
<td class="total">14.50</td>
</tr>
</tbody>
</table>
For the sake of understanding
// Get all inputs with type="number"
// that is a child of <td class="amount">.
var $amountInput = $('td.amount > input[type="number"]');
// Attach "input" event listener to the input fields
// so that we know when the value changes and handle the changes.
// In this case, the event handler is the function "updateTotal".
$amountInput.on('input', updateTotal);
function updateTotal(e){
// Get the `input` element that triggers this event.
var $thisInput = $(e.target);
// Get the value of $thisInput
var amount = $thisInput.val();
// The `value` is a string,
// so we need `parseInt` to make it a number.
// Use `parseInt` because quantity can't have decimals.
amount = parseInt(amount);
// Don't do anything if value is not valid
// else you will see NaN in result.
if (!amount || amount < 0)
return;
// Get the parent <tr> of this input field
var $parentRow = $thisInput.parent().parent();
// Find the <td class="total"> element
var $siblingTotal = $parentRow.find('.total');
// Find the <td class="cost"> element
var $siblingCost = $parentRow.find('.cost');
// Get the cost from <td class="cost"> element
var cost = $siblingCost.text();
// The "cost" is a string,
// so we need `parseFloat` to make it a number.
// Use `parseFloat` because cost can have decimals.
cost = parseFloat(cost);
// Calculate the total cost
var total = amount * cost;
// .toFixed(2) to force 2 decimal places
total = total.toFixed(2);
// Update the total cost into <td class="total"> element
$siblingTotal.text(total);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Input</th>
<th>Cost per item</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td class="amount"><input type="number" value="1"></td>
<td class="cost">27</td>
<td class="total">27</td>
</tr>
<tr>
<td class="amount"><input type="number" value="1"></td>
<td class="cost">14.50</td>
<td class="total">14.50</td>
</tr>
</tbody>
</table>
Note
If you still have difficulties understanding, you might want to read:
Why prefix "$" sign in only some variable names? (Generally called the Hungarian Notation)
What is td.amount > input[type="number"]?
What is jQuery's .on()?
What is e.target?
What is jQuery's .val()?
What is parseInt()?
What is parseFloat()?
What does !value mean?
Why do you return nothing?
What is jQuery's .parent()?
What is jQuery's .find()?
What is jQuery's .text()?
What is .toFixed()?
Related
I have the below HTML Table and I want to get the data between the tags which are sometimes single line and sometimes multi-line.
<table>
<tbody>
<tr>
<th>Role</th>
<th>Device Name</th>
<th>IP Address </th>
<th>MAC Address </th>
<th>Registered </th>
<th>Subscribers </th>
<th>Events </th>
</tr>
<tr>
<td>
CM
</td>
<td>
-
</td>
<td>192.168.7.110 </td>
<td>506182488323 </td>
<td>XYZ
</td>
<td> Shkdsd30ec1
</td>
<td>Events
</td>
</tr>
</tbody>
</table>
I want to generate the JSON with this table like the below code using javascript
{
"Role" : "CM",
"Device Name" : "-",
"IP Address" : "192.168.7.110",
"MAC Address" : "506182488323",
"Registered" : "XYZ",
"Subscribers" : "Shkdsd30ec1",
"Events" : "Events"
}
If there are more tags with the key should get incremented like Role->Role1->Role2 and so on.
Assuming that you have this table alone in your HTML body...
let t = document.getElementsByTagName("table");
let trs = t[0].getElementsByTagName("tr");
let oKeys = [], oVals = [];
let ths = trs[0].getElementsByTagName("th");
let tds = trs[1].getElementsByTagName("td");
ths = Array.from(ths);
tds = Array.from(tds);
ths.map( item => {
oKeys.push(item.innerText);
return ;
});
tds.map( item => {
oVals.push(item.innerText);
return ;
});
console.log("O keys ", oKeys);
console.log("oVals ", oVals);
let newObj = {};
oKeys.map( (key, i) => {
let val = oVals[i];
Object.assign(newObj, {[key] : val })
});
console.log(newObj);
<table id="myTable">
<tbody>
<tr>
<th>Role</th>
<th>Device Name</th>
<th>IP Address </th>
<th>MAC Address </th>
<th>Registered </th>
<th>Subscribers </th>
<th>Events </th>
</tr>
<tr>
<td>
CM
</td>
<td>
-
</td>
<td>192.168.7.110 </td>
<td>506182488323 </td>
<td>XYZ
</td>
<td> Shkdsd30ec1
</td>
<td>Events
</td>
</tr>
</tbody>
</table>
newObj holds your desired data. You can add more to the above logic..
Using jQuery for dom selection, this JS code should work
var myRows = [];
var headersText = [];
var $headers = $("th");
// Loop through grabbing everything
var $rows = $("tbody tr").each(function(index) {
$cells = $(this).find("td");
myRows[index] = {};
$cells.each(function(cellIndex) {
// Set the header text
if(headersText[cellIndex] === undefined) {
headersText[cellIndex] = $($headers[cellIndex]).text();
}
// Update the row object with the header/cell combo
myRows[index][headersText[cellIndex]] = $(this).text();
});
});
// Let's put this in the object like you want and convert to JSON (Note: jQuery will also do this for you on the Ajax request)
var myObj = {
"myrows": myRows
};
console.log(myRows);
this code snippet was collected from this thread
I have a table, which has an input at the end of each line.
Here is the input:
<td><input data-price='<?= floatval($row['Prix']); ?>' ?>' type="number" name="quantity" id="quantity"></td>
I have a script that takes the price of the data-price in the input and multiplies
it with the number in the input. Right now my script starts off by adding all of the prices, but then it multiplies the total by only the first input in my table.
How can I change my code so that it multiplies each price by the quantity in the input?
Here is the script:
document.getElementById("submit").onclick = function giveTotal() {
var total = 0;
var grandTotal = document.getElementById('grandTotal');
var quantity = document.getElementById('quantity');
var nodes = document.getElementsByName('quantity');
[].forEach.call(nodes, function(node) {
console.log(quantity.value);
console.log(node.dataset.price);
total += (parseFloat(node.dataset.price) * quantity.value)
})
grandTotal.innerHTML = total;
console.log('Total: ' + total);
};
IDs are unique -- no two elements can have the same ID. When you use document.getElementById(), it will return only the first element that matches that ID and no other.
You already have access to each input from your nodes variable, and you're already iterating over them in your forEach loop. So instead of multiplying by quantity.value, you should just be multiplying by node.value so that you're using the value of each specific input.
You need to select each table row by itself like this:
(In this example I assume your table has the id orders)
document.getElementById("submit").onclick = function giveTotal() {
// Get the table element (id="orders")
const $table = document.getElementById('orders');
// Get the grand total element
const $grandTotal = document.getElementById('grandTotal');
// Temporary variable
let total = 0;
// For each input element in the table add the price*value to total
table.querySelectorAll('input').forEach($input => {
total += (parseFloat($input.dataset.price) * $input.value)
});
// Write total to $grandTotal element
$grandTotal.innerText = total;
// Debug output
console.log('Total: ' + total);
};
You can get table rows and process them. Something like this.
document.getElementById('submit').onclick = function() {
var total = Array.from(document.querySelector('#cart tbody')
.querySelectorAll('tr')) //get array
.reduce((acc, cur) => acc + cur.querySelector('td:first-child').innerText * cur.querySelector('input').value, 0);
console.log(total);
};
<table id="cart">
<thead>
<tr>
<th>Price</th>
<th>Qty</th>
</tr>
</thead>
<tbody>
<tr>
<td>5.45</td>
<td><input name="qty" type="text" value="0" />
<!--number is ok too -->
</td>
</tr>
<tr>
<td>7.80</td>
<td><input name="qty" type="text" value="0" />
<!--number is ok too -->
</td>
</tr>
<tr>
<td>0.95</td>
<td><input name="qty" type="text" value="0" />
<!--number is ok too -->
</td>
</tr>
</tbody>
</table>
<button type="button" id="submit">Submit</button>
I've got a search box where as I type, table data gets filtered through and only matching results get shown. It works great; however, I want to make it better.
I want the code to ignore spaces and dashes. I'd prefer make it easy to add additional characters I want it to ignore as well in the future..
For instance...
Product Table
FH-54
TDN 256
TDN25678
FH54
In the search box, if I type FH54, I'd like both the FH-54 and the FH54 to show up. If I type in FH-54 I'd also like the FH54 and the FH-54 to show up and so on to include FH 54 as well.
If I type in TDN2 or TDN 2 in the search box, I'd like TDN 256 and TDN25678 to show up.
<b>Product Search</b><br /><form class="formatted">
<input id="Search" data-class="search_product" type="text" /></form>
<script type="text/javascript">
$('#Search').on('keyup', function(e) {
$("#noData").remove();
var value = $(this).val();
value = value.replace(/\\/g, '');
var patt = new RegExp(value, "i");
var sw = 0;
var counter = 0;
$('#Data tbody').find('tr').each(function() {
counter++;
if (!($(this).find('td').text().search(patt) >= 0)) {
$(this).not('#header').hide();
sw++;
} else if (($(this).find('td').text().search(patt) >= 0)) {
$(this).show();
}
});
if (sw == counter) {
$("#Data tbody").append(`<tr id="noData">
<td colspan="3">No data</td>
</tr>`);
} else {
$("#noData").remove();
}
});
</script>
I've tried to reconstruct your scenario the best I could and made a working example.
As per your requirement to ignore all spaces and dashes: How about removing spaces and dashes from search string and from your values within the columns?
$('#Search').on('keyup', function(e) {
$("#noData").remove();
var value = $(this).val();
var spacesAndDashes = /\s|-/g;
value = value.replace(spacesAndDashes, "");
var patt = new RegExp(value, "i");
var sw = 0;
var counter = 0;
$('#Data tbody').find('tr').each(function() {
counter++;
if (!($(this).find('td').text().replace(spacesAndDashes, "").search(patt) >= 0)) {
$(this).not('#header').hide();
sw++;
} else if (($(this).find('td').text().replace(spacesAndDashes, "").search(patt) >= 0)) {
$(this).show();
}
});
if (sw == counter) {
$("#Data tbody").append(`<tr id="noData">
<td colspan="3">No data</td>
</tr>`);
} else {
$("#noData").remove();
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<b>Product Search</b>
<br />
<form class="formatted">
<input id="Search" data-class="search_product" type="text" />
</form>
<table id="Data">
<thead>
<tr>
<th>Product Table</th>
</tr>
</thead>
<tbody>
<tr>
<td>FH-54</td>
</tr>
<tr>
<td>TDN 256</td>
</tr>
<tr>
<td>FH54</td>
</tr>
<tr>
<td>FH 54</td>
</tr>
<tr>
<td>TDN25678</td>
</tr>
</tbody>
</table>
Right now I'm learning nodes. before that I'm sorry if my question isn't specific please let me know how to state it better.
This code is for deleting element attributes.
There's a color in the table column and when I press button the attribute bgcolor in td tag is gone.
When I run it, it always show tdelement is null? while I already use for statement to loop and check it.
And please answer it using Javascript.
function removeColor(color)
{
var table = document.getElementById("multi");
var tdList = table.getElementsByTagName("td");
// Loop through list <td> elements.
for (var i = 0; i <= tdList.length; i++)
{
var tdElement = tdList.item(i);
// Get the attribute.
var colorAtt = tdElement.getAttribute("value");
//If the attribute matches the color then delete attributes
if (colorAtt == color)
{
tdElement.removeAttributeNode(colorAtt);
}
}
}
// the end for javascript -----------------
<table id="multi" border="1">
<tr>
<td></td>
<td bgcolor="#ff0000">1</td>
<td bgcolor="#008000">2</td>
<td bgcolor="#ffff00">3</td>
</tr>
<tr>
<td bgcolor="#ff0000">1</td>
<td bgcolor="#ff0000">1</td>
<td bgcolor="#008000">2</td>
<td bgcolor="#ffff00">3</td>
</tr>
<tr>
<td bgcolor="#008000">2</td>
<td bgcolor="#008000">2</td>
<td bgcolor="#008000">4</td>
<td bgcolor="#ffff00">6</td>
</tr>
<tr>
<td bgcolor="#ffff00">3</td>
<td bgcolor="#ffff00">3</td>
<td bgcolor="#ffff00">6</td>
<td bgcolor="#ffff00">9</td>
</tr>
</table>
<button onclick="removeColor('#ff0000')">Remove Red Background</button><br>
try this
function removeColor(color)
{
var table = document.getElementById("multi");
var tdList = table.getElementsByTagName("td");
// Loop through list <td> elements.
for (var i = 0; i <= tdList.length; i++)
{
var tdElement = tdList.item(i);
// Get the attribute.
var colorAtt = tdElement.getAttributeNode("bgcolor");
//If the attribute matches the color then delete attributes
if (colorAtt && (colorAtt.value == color))
{
tdElement.removeAttributeNode(colorAtt);
}
}
}
using .getAttribute("value"); would try to get the attribute 'value' from the element. where you need to get the node .getAttributeNode("bgcolor");.
Fiddle
I have a Table whose <td> values varies depending upon the inputs given in form, I am using Tangle to make a reactive document. Is it posible to detect if the value of <td>changes to any negative number? If so, then it must change its color to red!
Can Javascripting or html tags itself solve this problem?
Please help!
My change will be on profitLossIn1,profitLossIn2,profitLossIn3.
Here is my html:
<table>
<tr>
<th>Name</th>
<th>Cost</th>
<th>Revenue</th>
<th>Result Profit/Loss</th>
</tr>
<tr>
<td><input id='NameInn1' type='text' NAME="NameInn1"></td>
<td><span class="TKNumberField" data-var="CostIn1"></span></td>
<td><b data-var="revenueIn1"> Cost</b></td>
<td><b data-var="profitLossIn1"> dollars</b></td>
</tr>
<tr>
<td><input id='NameInn2' type='text' NAME="NameInn2"></td>
<td><span class="TKNumberField" data-var="CostIn2"></span></td>
<td><b data-var="revenueIn2"> Cost</b></td>
<td><b data-var="profitLossIn2"> dollars</b></td>
</tr>
<tr>
<td><input id='NameInn3' type='text' NAME="NameInn3"></td>
<td><span class="TKNumberField" data-var="CostIn3"></span></td>
<td><b data-var="revenueIn3"> Cost</b></td>
<td><b data-var="profitLossIn3"> dollars</b></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td><b data-var="totalRevenueIn"> dollars</b></td>
</tr>
</table>
I am trying this:
var inputs = document.getElementById("profitLossOut1");
console.log(inputs.value);
inputs.onchange = function () {
console.log("Checking IF condition");
if ((parseInt(this.value)).match("-") == true) this.parentNode.style.background = "red";
};
maybe this can be helpful: http://jsfiddle.net/tz7WB/
JQUERY CODE
$(":input").on("change", function () {
if (parseInt($(this).val()) < 0) $(this).closest("td").css("background", "red");
})
try to type any negative number in the inputs
with pure js: http://jsfiddle.net/tz7WB/1/
JS CODE
var inputs = document.getElementsByTagName("input");
for (var x = 0; x < inputs.length; x++) {
inputs[x].onchange = function () {
if (parseInt(this.value) < 0) this.parentNode.style.background = "red";
};
}
Assuming I understand your question correctly, you don't want to check for negative values of the inputs, you want to check for negative values of the tangle-generated text values.
This code should be more of what you're looking for, and it works as long as the text content of your data-var elements starts with the number. If not, the number parsing logic will need to be improved:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input").change(function(e) {
var $target = $(e.target);
var checkNeg = function(c) {
for(var i=0,$ci; i<c.length; i++) {
$ci = $(c[i]);
if(parseInt($ci.text()) < 0) $ci.css("color", "red");
else $ci.css("color", "black");
}
};
checkNeg($target.parents("table").find("[data-var]"));
});
});
</script>
Consider using knockout.js for your scenario, you can use it to easily format your UI elements according to the underlying data. Take a look at the examples: http://knockoutjs.com/examples/
Add jquery change events for each of input boxes . Below is sample code
$("#NameInn1").change(function(){
var input = $("#NameInn1").val();
if(input<10){
$("#NameInn1").css("background-color","red");
}
});