Show/Hide Not Working When Fields Added Using .after () Function [duplicate] - javascript

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 6 years ago.
When I add fields using the jQuery .after() function, the show/hide functionality does not work on those fields.
Here's a JSFiddle that demonstrates the issue:
JSFiddle Demo
The show/hide functionality works on the first row, but does not work on any rows added after that one. I think the code being written after the page has been loaded might be the issue, but I'm not certain. If that's the case, is there a work around other than hard coding a certain amount of rows?
Here's the code I'm working with:
CSS:
#Table {
font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse:collapse;
}
#Table td, #Table th {
font-size:1em;
border:1px solid #98bf21;
padding:3px 7px 2px 7px;
}
#Table th {
font-size:1.4em;
text-align:left;
padding-top:5px;
padding-bottom:4px;
background-color:#A7C942;
color:#fff;
}
#Table tr.alt td {
color:#000;
background-color:#EAF2D3;
}
HTML:
<table style="width: 70%" id="Table" name="Table">
<tr>
<th>#</th>
<th>Cause</th>
</tr>
<tr>
<td>1</td>
<td>
<select name='report_cause2' id='report_cause2' class="report_cause">
<option value='default'>-</option>
<option value='other'>Other, Not Listed</option>
</select>
<p class="cause_details">
<input type="text" name="cause_detail_info" id="cause_detail_info" placeholder="Type cause here" size="48" maxlength="50" class="textbox required" value="" />
</p>
</td>
</tr>
</table>
<input type="button" id="btnAdd" name="btnAdd" value="Add More" class="button" />
jQuery:
var count_2 = 5;
var table_count2 = 1;
$(document).ready(function () {
$('.cause_details').hide();
$('.report_cause').change(function () {
if ($(this).val() == 'other') {
$(this).parent().find('.cause_details').show();
} else {
$(this).parent().find('.cause_details').hide();
}
});
$('#btnAdd').click(function () {
count_2 = count_2 + 2;
table_count2 = table_count2 + 1;
$('#Table tr:last').after('<tr><td>' + table_count2 + '</td>' +
'<td>' +
'<select name=\"report_cause' + count_2 + '\" id=\"report_cause' + count_2 + '\" class=\"report_cause\">' +
'<option value=\'default\'>-</option>' +
'<option value=\'other\'>Other, Not Listed</option>' +
'</select>' +
'<p class=\"cause_details\">' +
'<input type=\"text\" name=\"cause_detail_info' + count_2 + '\" id=\"cause_detail_info' + count_2 + '\" placeholder=\"Type cause here\" size=\"48\" maxlength=\"50\" class=\"textbox required\" value=\"\" />' +
'</p>' +
'</td></tr>');
});
});

This:
$('.report_cause').change(function () {
Only applies to the .report_cause elements that existed when it was called. To handle new elements, you need a delegated handler:
$(document).on('change', '.report_cause', function(){
Additionally, if you want the new elements initially hidden, modify your output HTML accordingly:
'<p class=\"cause_details\" style=\"display:none\">'+
var count_2 = 5;
var table_count2 = 1;
$(document).ready(function() {
$('.cause_details').hide();
$(document).on('change', '.report_cause', function() {
if ($(this).val() == 'other') {
$(this).parent().find('.cause_details').show();
} else {
$(this).parent().find('.cause_details').hide();
}
});
$('#btnAdd').click(function() {
count_2 = count_2 + 2;
table_count2 = table_count2 + 1;
$('#Table tr:last').after('<tr><td>' + table_count2 + '</td>' +
'<td>' +
'<select name=\"report_cause' + count_2 + '\" id=\"report_cause' + count_2 + '\" class=\"report_cause\">' +
'<option value=\'default\'>-</option>' +
'<option value=\'other\'>Other, Not Listed</option>' +
'</select>' +
'<p class=\"cause_details\" style=\"display:none\">' +
'<input type=\"text\" name=\"cause_detail_info' + count_2 + '\" id=\"cause_detail_info' + count_2 + '\" placeholder=\"Type cause here\" size=\"48\" maxlength=\"50\" class=\"textbox required\" value=\"\" />' +
'</p>' +
'</td></tr>');
});
});
#Table {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
}
#Table td,
#Table th {
font-size: 1em;
border: 1px solid #98bf21;
padding: 3px 7px 2px 7px;
}
#Table th {
font-size: 1.4em;
text-align: left;
padding-top: 5px;
padding-bottom: 4px;
background-color: #A7C942;
color: #fff;
}
#Table tr.alt td {
color: #000;
background-color: #EAF2D3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table style="width: 70%" id="Table" name="Table">
<tr>
<th>#</th>
<th>Cause</th>
</tr>
<tr>
<td>1</td>
<td>
<select name='report_cause2' id='report_cause2' class="report_cause">
<option value='default'>-</option>
<option value='other'>Other, Not Listed</option>
</select>
<p class="cause_details">
<input type="text" name="cause_detail_info" id="cause_detail_info" placeholder="Type cause here" size="48" maxlength="50" class="textbox required" value="" />
</p>
</td>
</tr>
</table>
<input type="button" id="btnAdd" name="btnAdd" value="Add More" class="button" />

Try this. The problem is that when you create a dynamic element, you need to again register change event on $('.report_cause').
$(document).ready(function(){
$('.cause_details').hide();
BindChange();
$('#btnAdd').click(function(){
count_2 = count_2 + 2;
table_count2 = table_count2 + 1;
$('#Table tr:last').after('<tr><td>'+table_count2+'</td>'+
'<td>'+
'<select name=\"report_cause'+count_2+'\" id=\"report_cause'+count_2+'\" class=\"report_cause\">'+
'<option value=\'default\'>-</option>'+
'<option value=\'other\'>Other, Not Listed</option>'+
'</select>'+
'<p class=\"cause_details\">'+
'<input type=\"text\" name=\"cause_detail_info'+count_2+'\" id=\"cause_detail_info'+count_2+'\" placeholder=\"Type cause here\" size=\"48\" maxlength=\"50\" class=\"textbox required\" value=\"\" />'+
'</p>'+
'</td></tr>');
BindChange();
});
});
function BindChange()
{
$('.report_cause').bind("change",function(){
if ($(this).val() == 'other'){
$(this).parent().find('.cause_details').show();
}else{
$(this).parent().find('.cause_details').hide();
}
});
}
https://jsfiddle.net/hnj6ed1y/12/

When you create the elements dynamically, you need to use event delegation to handle the events on them, so based on your jQuery version use .bind or .on API.
Just change in your code to:
$(document).on('change', '.report_cause', function () {
if ($(this).val() == 'other') {
$(this).parent().find('.cause_details').show();
} else {
$(this).parent().find('.cause_details').hide();
}
});

Related

Script not running on Internet Explorer

My script is working fine on everything except internet explorer. I'm not sure if it because I am using unsupported syntax or functions or what but if someone could take a look and see if anything stands out to them it would be really appreciated.
The basic implementation of the script is to create a simple shopping cart list when users click on a button. The total increments to include the added item and the item name, quantity and price is listed.
I have other scripts that work on my page so I know it is possible to implement onclick for example but I am unsure how to proceed here.
<div class="product-div" id="big-blue-barrel-div">
<h3>Big Blue barrel- $199</h3>
<div class="img-div">
<img src="images/barrel-pic.png" alt="picture of barrel" class="product-img">
</div>
<span>Quantity: </span>
<input class="qty bigBlueBarrelQty" type="number" name="qty" value="1" min="1" id="bigBlueBarrelQty">
<button type="button" onclick="addData(this.id, 'bigBlueBarrelQty')" name="button" id="bigBlueBarrel">Add to Cart</button>
</div>
var values = {
bigBlueBarrel: {
name: "Big Blue Barrel",
price: 199
},
bigBlueBox: {
name: "Big Blue Box",
price: 399
},
babyBlueBarrel: {
name: "Baby Blue Barrel",
price: 99
}
}
var total = 0;
var rowCount = 1;
function addData(clicked_id, quantity) {
var price = values[clicked_id].price;
var qty = document.getElementById(quantity).value;
var lineTotal = price * qty;
total += lineTotal;
document.getElementById("total").innerHTML = total;
addRow(clicked_id, qty, lineTotal);
if (qty == 1) {
alert(`${qty} ${values[clicked_id].name} has been added to your cart!
Scroll down to view your cart.`)
} else if (qty > 1) {
alert(`${qty} ${values[clicked_id].name}s have been added to your cart!
Scroll down to view your cart`);
}
}
function addRow(clicked_id, qty, lineTotal) {
var rows = "";
if (rowCount % 2 != 0 ) {
rows += `<tr class="odd"><td>${values[clicked_id].name}</td><td class="row-qty">${qty}</td><td>$${lineTotal}</td><td class="delete"><button onclick="deleteRow(this)" class="delete-btn">delete</button></td></tr>`;
$(rows).appendTo("#cart tbody");
rowCount++;
} else {
rows += `<tr class="even"><td>${values[clicked_id].name}</td><td class="row-qty">${qty}</td><td>$${lineTotal}</td><td class="delete"><button onclick="deleteRow(this)" class="delete-btn">delete</button></td></tr>`;
$(rows).appendTo("#cart tbody");
rowCount++;
}
}
function deleteRow(r) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("cart").deleteRow(i);
}
Any thoughts would be appreciated.
A lot of features in ES6 will not work in IE.
Template literals for example:
${qty} ${values[clicked_id].name}
In this case you need to rewrite your template literals into normal strings using quotes:
alert(qty + " " + values[clicked_id].name + " has been added to your cart!"+
"\n\n" +
"Scroll down to view your cart.");
This website:
https://caniuse.com/#search=template%20literals
and MDN are valuable resources when I comes to compatibility.
Rewrite:
Tested on IE and it works!
var values = {
bigBlueBarrel: {
name: "Big Blue Barrel",
price: 199
},
bigBlueBox: {
name: "Big Blue Box",
price: 399
},
babyBlueBarrel: {
name: "Baby Blue Barrel",
price: 99
}
}
var total = 0;
var rowCount = 1;
function addData(clicked_id, quantity) {
var price = values[clicked_id].price;
var qty = document.getElementById(quantity).value;
var lineTotal = price * qty;
total += lineTotal;
document.getElementById("total").innerHTML = total;
addRow(clicked_id, qty, lineTotal);
if (qty == 1) {
/*alert(`${qty} ${values[clicked_id].name} has been added to your cart!
Scroll down to view your cart.`)*/
alert(qty + " " + values[clicked_id].name + " has been added to your cart!" +
"\n\n" +
"Scroll down to view your cart.");
} else if (qty > 1) {
/*alert(`${qty} ${values[clicked_id].name}s have been added to your cart!
Scroll down to view your cart`);*/
alert(qty + " " + values[clicked_id].name + "s has been added to your cart!" +
"\n\n" +
"Scroll down to view your cart.");
}
}
function addRow(clicked_id, qty, lineTotal) {
var rows = "";
//optimizing this:
/*rows += `<tr class="odd"><td>${values[clicked_id].name}</td><td class="row-qty">${qty}</td><td>$${lineTotal}</td><td class="delete"><button onclick="deleteRow(this)" class="delete-btn">delete</button></td></tr>`;*/
rows += '<tr class="' + (rowCount % 2 ? 'even' : 'odd') + '"><td>' + values[clicked_id].name + '</td><td class="row-qty">' + qty + '</td><td>' + lineTotal + '</td><td class="delete"><button onclick="deleteRow(this)" class="delete-btn">delete</button></td></tr>';
$(rows).appendTo("#cart tbody");
rowCount++;
}
function deleteRow(r) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("cart").deleteRow(i);
}
table#cart {
margin: 40px;
border: 1px solid #e3e3e3;
border-collapse: collapse;
}
table#cart td {
padding: 10px;
border-right: 1px dashed #f2f2f2;
}
table#cart td > button{
padding: 10px;
border: 1px solid #f2f2f2;
background-color: #ff4444;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product-div" id="big-blue-barrel-div">
<h3>Big Blue barrel- $199</h3>
<div class="img-div">
<img src="images/barrel-pic.png" alt="picture of barrel" class="product-img">
</div>
<span>Quantity: </span>
<input class="qty bigBlueBarrelQty" type="number" name="qty" value="1" min="1" id="bigBlueBarrelQty">
<button type="button" onclick="addData(this.id, 'bigBlueBarrelQty')" name="button" id="bigBlueBarrel">Add to Cart</button>
</div>
<!-- added for testing -->
<table id="cart">
<tbody>
</tbody>
</table>
Total: <span id="total"></span>

How jQuery invoices form and delete how buttons add

I am currently working on a dynamic invoice system for myself. But I can't make it work correctly.
I want to add a delete button to this form but I cannot do so.
I have an invoice table like this in HTML:
$('#addRow').click(function () {
addItem();
});
$('#items_table').on('keyup', '.update', function () {
var key = event.keyCode || event.charCode; // if the user hit del or backspace, dont do anything
if( key == 8 || key == 46 ) return false;
calculateTotals();
});
$('#taxPercentage').change(function () {
calculateTotals(); // user changed tax percentage, recalculate everything
});
function calculateTotals(){
// get all of the various input typs from the rows
// each will be any array of elements
var nameElements = $('.row-name');
var quantityElements = $('.row-quantity');
var taxElements = $('.row-tax');
var priceElements = $('.row-price');
var totalElements = $('.row-total');
// get the bottom table elements
var taxPercentageElement =$('#taxPercentage');
var subTotalElement =$('#subTotal');
var totalTaxElement =$('#totalTax');
var grandTotalElement =$('#grandTotal');
var subTotal=0;
var taxTotal=0;
var grandTotal=0;
$(quantityElements).each(function(i,e){
// get all the elements for the current row
var nameElement = $('.row-name:eq(' + i + ')');
var quantityElement = $('.row-quantity:eq(' + i + ')');
var taxElement = $('.row-tax:eq(' + i + ')');
var priceElement = $('.row-price:eq(' + i + ')');
var totalElement = $('.row-total:eq(' + i + ')');
// get the needed values from this row
var qty = quantityElement.val().trim().replace(/[^0-9$.,]/g, ''); // filter out non digits like letters
qty = qty == '' ? 0 : qty; // if blank default to 0
quantityElement.val(qty); // set the value back, in case we had to remove soemthing
var price = priceElement.val().trim().replace(/[^0-9$.,]/g, '');
price = price == '' ? 0 : price; // if blank default to 0
priceElement.val(price); // set the value back, in case we had to remove soemthing
// get/set row tax and total
// also add to our totals for later
var rowPrice = (price * 1000) * qty
subTotal = subTotal + rowPrice;
var tax = taxPercentageElement.val() * rowPrice;
taxElement.val((tax / 1000).toFixed(2));
taxTotal = taxTotal + tax;
var total = rowPrice + tax
totalElement.val((total / 1000).toFixed(2));
grandTotal = grandTotal + total;
});
// set the bottom table values
subTotalElement.val((subTotal / 1000).toFixed(2));
totalTaxElement.val((taxTotal / 1000).toFixed(2));
grandTotalElement.val((grandTotal / 1000).toFixed(2));
}
function addItem() {
var itemRow =
'<tr>' +
'<td><input type="text" class="form-control row-name" placeholder="Item name" /></td>' +
'<td><input type="text" class="form-control update row-quantity" placeholder="Quantity" /></td>' +
'<td><input type="text" class="form-control update row-tax" placeholder="Tax" /></td>' +
'<td><input type="text" class="form-control update row-price" placeholder="Price" /></td>' +
'<td><input type="text" class="form-control row-total" disabled placeholder="0,00" /></td>' +
'</tr>';
$("#items_table").append(itemRow);
}
addItem(); //call function on load to add the first item
button{
font-size:18px;
}
.myTable {
background-color:#ffaa56;
}
.myTable {
border-collapse: collapse;
border-spacing: 0;
width:100%;
height:100%;
margin:0px;
padding:0px;
}
.myTable tr:last-child td:last-child {
-moz-border-radius-bottomright:0px;
-webkit-border-bottom-right-radius:0px;
border-bottom-right-radius:0px;
}
.myTable tr:first-child td:first-child {
-moz-border-radius-topleft:0px;
-webkit-border-top-left-radius:0px;
border-top-left-radius:0px;
}
.myTable tr:first-child td:last-child {
-moz-border-radius-topright:0px;
-webkit-border-top-right-radius:0px;
border-top-right-radius:0px;
}
.myTable tr:last-child td:first-child {
-moz-border-radius-bottomleft:0px;
-webkit-border-bottom-left-radius:0px;
border-bottom-left-radius:0px;
}
.myTable tr:hover td {
}
#items_table tr:nth-child(odd) {
background-color:#ffffff;
}
#items_table tr:nth-child(even) {
background-color:#ffd0a3;
}
.myTable td {
vertical-align:middle;
border:1px solid #000000;
border-width:0px 1px 1px 0px;
text-align:left;
padding:7px;
font-size:10px;
font-family:Arial;
font-weight:normal;
color:#000000;
}
.myTable tr:last-child td {
border-width:0px 1px 0px 0px;
}
.myTable tr td:last-child {
border-width:0px 0px 1px 0px;
}
.myTable tr:last-child td:last-child {
border-width:0px 0px 0px 0px;
}
html page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button id="addRow">Add a row</button><br><br>
<table class="myTable">
<thead>
<tr>
<th>Item Name</th>
<th>Quantity</th>
<th>Tax</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody id="items_table"></tbody>
<tfoot>
<tr>
<th>Item Name</th>
<th>Quantity</th>
<th>Tax</th>
<th>Price</th>
<th>Total</th>
</tr>
</tfoot>
</table>
<br>
<br>
<table class="myTable" style="width:70%">
<thead>
<tr>
<th>Tax Percentage</th>
<th>Sub Total</th>
<th>Total Tax</th>
<th>Grand Total</th>
</tr>
</thead>
<tbody id="items_table">
<tr>
<td>
<select name="" id="taxPercentage" class="form-control">
<option value=".10">10%</option>
<option value=".15">15%</option>
</select>
<td><input type="text" class="form-control" id="subTotal" disabled placeholder="0,00" /></td>
<td><input type="text" class="form-control" id="totalTax" disabled placeholder="0,00" /></td>
<td><input type="text" class="form-control" id="grandTotal" disabled placeholder="0,00" /></td>
</tr>
</tbody>
<tfoot>
</tfoot>
</table>
I am currently out of ideas on how to do this correctly. So, all I need is once I filled 1 item row, the tax gets in the total table added, and once I change that tax in that row, it changes below as well, and the price has to be changed as well.
Can someone set me on the right track?
I want to add delete button to this form but I can not do it
The key here is to understand that event handlers usually can be set only on the elements that are present on the page at the moment of setting. Your code failed because you add rows dynamically - they didn't exist when you tried to assign an event handler. However, jQuery provides us with the special form of on() function that covers what we need in this case:
$('already present parent element selector').on("click", "existing/added later element selector", function () {
//code
});
So, in order to sort out your problem your code should look like this:
$('body').on("click", "#delRow", function () {
delItem($(this));
});
function delItem(elem) {
elem.parents("tr").remove();
calculateTotals();
}
Note that you have to add #delRow button to your template in addItem() function and corresponding <th> cells in the markup.
Regarding the whole thing, I would also make the tax cell disabled because it wouldn't make sense if users could edit it since the tax sum is defined by percent value below (either 10% or 15%). And the taxes are usually imposed by the govs. and known in advance. I mean you cannot just pay 5.745632% instead of 15% defined by a law.
Also I spotted one minor issue: when I remove symbols in the price cell the update doesn't get executed and the related cells' values don't change accordingly. You might want to read about input event on MDN.
In general it works fine if I understood your ideas correctly:
$('#addRow').on("click", function () {
addItem();
});
$('body').on("click", "#delRow", function () {
delItem($(this));
});
$('#items_table').on('input', '.update', function () {
var key = event.keyCode || event.charCode; // if the user hit del or backspace, dont do anything
if( key == 8 || key == 46 ) return false;
calculateTotals();
});
$('#taxPercentage').change(function () {
calculateTotals(); // user changed tax percentage, recalculate everything
});
function calculateTotals(){
// get all of the various input typs from the rows
// each will be any array of elements
var nameElements = $('.row-name');
var quantityElements = $('.row-quantity');
var taxElements = $('.row-tax');
var priceElements = $('.row-price');
var totalElements = $('.row-total');
// get the bottom table elements
var taxPercentageElement =$('#taxPercentage');
var subTotalElement =$('#subTotal');
var totalTaxElement =$('#totalTax');
var grandTotalElement =$('#grandTotal');
var subTotal=0;
var taxTotal=0;
var grandTotal=0;
$(quantityElements).each(function(i,e){
// get all the elements for the current row
var nameElement = $('.row-name:eq(' + i + ')');
var quantityElement = $('.row-quantity:eq(' + i + ')');
var taxElement = $('.row-tax:eq(' + i + ')');
var priceElement = $('.row-price:eq(' + i + ')');
var totalElement = $('.row-total:eq(' + i + ')');
// get the needed values from this row
var qty = quantityElement.val().trim().replace(/[^0-9$.,]/g, ''); // filter out non digits like letters
qty = qty == '' ? 0 : qty; // if blank default to 0
quantityElement.val(qty); // set the value back, in case we had to remove soemthing
var price = priceElement.val().trim().replace(/[^0-9$.,]/g, '');
price = price == '' ? 0 : price; // if blank default to 0
priceElement.val(price); // set the value back, in case we had to remove soemthing
// get/set row tax and total
// also add to our totals for later
var rowPrice = (price * 1000) * qty
subTotal = subTotal + rowPrice;
var tax = taxPercentageElement.val() * rowPrice;
taxElement.val((tax / 1000).toFixed(2));
taxTotal = taxTotal + tax;
var total = rowPrice + tax
totalElement.val((total / 1000).toFixed(2));
grandTotal = grandTotal + total;
});
// set the bottom table values
subTotalElement.val((subTotal / 1000).toFixed(2));
totalTaxElement.val((taxTotal / 1000).toFixed(2));
grandTotalElement.val((grandTotal / 1000).toFixed(2));
}
function delItem(elem) {
elem.parents("tr").remove();
calculateTotals();
}
function addItem() {
var itemRow =
'<tr>' +
'<td><button id="delRow">Delete</button></td><td><input type="text" class="form-control row-name" placeholder="Item name" /></td>' +
'<td><input type="text" class="form-control update row-quantity" placeholder="Quantity" /></td>' +
'<td><input type="text" disabled class="form-control update row-tax" placeholder="Tax" /></td>' +
'<td><input type="text" class="form-control update row-price" placeholder="Price" /></td>' +
'<td><input type="text" class="form-control row-total" disabled placeholder="0,00" /></td>' +
'</tr>';
$("#items_table").append(itemRow);
}
addItem(); //call function on load to add the first item
button{
font-size:18px;
}
.myTable {
background-color:#ffaa56;
}
.myTable {
border-collapse: collapse;
border-spacing: 0;
width:100%;
height:100%;
margin:0px;
padding:0px;
}
.myTable tr:last-child td:last-child {
-moz-border-radius-bottomright:0px;
-webkit-border-bottom-right-radius:0px;
border-bottom-right-radius:0px;
}
.myTable tr:first-child td:first-child {
-moz-border-radius-topleft:0px;
-webkit-border-top-left-radius:0px;
border-top-left-radius:0px;
}
.myTable tr:first-child td:last-child {
-moz-border-radius-topright:0px;
-webkit-border-top-right-radius:0px;
border-top-right-radius:0px;
}
.myTable tr:last-child td:first-child {
-moz-border-radius-bottomleft:0px;
-webkit-border-bottom-left-radius:0px;
border-bottom-left-radius:0px;
}
.myTable tr:hover td {
}
#items_table tr:nth-child(odd) {
background-color:#ffffff;
}
#items_table tr:nth-child(even) {
background-color:#ffd0a3;
}
.myTable td {
vertical-align:middle;
border:1px solid #000000;
border-width:0px 1px 1px 0px;
text-align:left;
padding:7px;
font-size:10px;
font-family:Arial;
font-weight:normal;
color:#000000;
}
.myTable tr:last-child td {
border-width:0px 1px 0px 0px;
}
.myTable tr td:last-child {
border-width:0px 0px 1px 0px;
}
.myTable tr:last-child td:last-child {
border-width:0px 0px 0px 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="addRow">Add a row</button><br><br>
<table class="myTable">
<thead>
<tr><th>Delete</th>
<th>Item Name</th>
<th>Quantity</th>
<th>Tax</th>
<th>Price per unit</th>
<th>Total</th>
</tr>
</thead>
<tbody id="items_table"></tbody>
<tfoot>
<tr><th>Delete</th>
<th>Item Name</th>
<th>Quantity</th>
<th>Tax</th>
<th>Price per unit</th>
<th>Total</th>
</tr>
</tfoot>
</table>
<br>
<br>
<table class="myTable" style="width:70%">
<thead>
<tr>
<th>Tax Percentage</th>
<th>Sub Total</th>
<th>Total Tax</th>
<th>Grand Total</th>
</tr>
</thead>
<tbody id="items_table">
<tr>
<td>
<select name="" id="taxPercentage" class="form-control">
<option value=".10">10%</option>
<option value=".15">15%</option>
</select>
<td><input type="text" class="form-control" id="subTotal" disabled placeholder="0,00" /></td>
<td><input type="text" class="form-control" id="totalTax" disabled placeholder="0,00" /></td>
<td><input type="text" class="form-control" id="grandTotal" disabled placeholder="0,00" /></td>
</tr>
</tbody>
<tfoot>
</tfoot>
</table>
As for your additional question - you can choose a locale to treat numbers as money in your country's format. It can be done by toLocaleString():
var num1 = 145636,
num2 = 145636;
console.log(num1.toLocaleString('en-US', {style: 'currency', currency: 'USD'})); // US format - 145,636
console.log(num2.toLocaleString('en-IN', {style: 'currency', currency: 'INR'})); // Indian format - 1,45,636
How can I separate the numbers that I write to price into a comma?
sample:
1,500
1,456,36

how to remove row and add css class when button clicked

here is the fiddle
https://jsfiddle.net/shaswatatripathy/enq0kfqL/2/
how to write the remove function and how to add a css class to a row which is clicked .
1.when i click remove the clicked row should get removed
when i click the row - row should get highlightrow css class attached
also have to check if the table has any rows or not and put it in a var
at a time only one row should be in red (clicked row) if no row is selected the remove button should not be visible
HTML
col1header
col2header
CSS
.visibilityHide {
visibility: hidden;
}
.highlightRow{
color:red;
}
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
JS or Jquery
function add()
{var addRow1;
var addRow2;
addRow1 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow1" + "</td><td>" + "col2valuerow1" + "</td></tr>";
addRow2 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow2" + "</td><td>" + "col2valuerow2" + "</td></tr>";
$("#myTableid tbody").append(addRow1);
$("#myTableid tbody").append(addRow2);
}
function remove()
{
}
function getdetails(row)
{
$('#removerow').css('visibility', 'visible');
}
This is the updated javascript code. This will meet all your requirements.
function add()
{
var addRow1;
var addRow2;
addRow1 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow1" + "</td><td>" + "col2valuerow1" + "</td></tr>";
addRow2 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow2" + "</td><td>" + "col2valuerow2" + "</td></tr>";
$("#myTableid tbody").append(addRow1);
$("#myTableid tbody").append(addRow2);
}
function remove()
{
$(".highlightRow").remove();
$('#removerow').addClass('visibilityHide');
$("#dropDown").prop("disabled", $("#myTableid tbody tr").length > 0);
}
function getdetails(row)
{
$('#removerow').toggleClass('visibilityHide', $("#myTableid tbody tr").length === 0);
$(".highlightRow").removeClass("highlightRow");
$(row).addClass("highlightRow");
}
Try this one. if it'll work
function add(){
var addRow1;
var addRow2;
addRow1 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow1" + "</td><td>" + "col2valuerow1" + "</td></tr>";
addRow2 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow2" + "</td><td>" + "col2valuerow2" + "</td></tr>";
$("#myTableid tbody").append(addRow1);
$("#myTableid tbody").append(addRow2);
}
function remove(){
$('.removeClass').remove(); //remove clicked row
if($('table tbody tr').length <=0){
$('#removerow').hide();
}
if($('table tbody tr').length===0) {
alert('This last child has been removed');
$("#dropDown").prop("disabled", false);
}
}
function getdetails(row){
$('#removerow').show();
$(row).addClass('removeClass'); //add class on clicked row
}
.highlightRow{
color:red;
}
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
/* styling for added class so that it looks something different when class added */
.removeClass{
color:red;
}
#removerow {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table id="myTableid">
<thead>
<th>
col1header
</th>
<th>
col2header
</th>
</thead>
<tbody>
</tbody>
</table>
<input type="button" id ="addrows" value="add" onclick="add()" />
<input type="button" id="removerow" value="remove" onclick="remove()" class="visibilityHide" />
Checking if the row is the last one is this part of the code
if($('table tbody tr').length==0) {
alert('This last child has been removed');
$("#dropDown").prop("disabled", false);
}
Do it like below (All solutions what you asked for):-
function add(){
var addRow1;
var addRow2;
addRow1 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow1" + "</td><td>" + "col2valuerow1" + "</td></tr>";
addRow2 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow2" + "</td><td>" + "col2valuerow2" + "</td></tr>";
$("#myTableid tbody").append(addRow1);
$("#myTableid tbody").append(addRow2);
}
function remove(){
var index = parseInt($('.removeClass').index())+1;
$('.removeClass').remove(); //remove clicked row
$('.removed_row').html("<strong>row number "+index+ " removed</strong>");
if($('table tbody tr').length <=0){
$('#removerow').hide();
}
}
function getdetails(row){
$('#removerow').css('display', 'block');
$('.removeClass').removeClass('removeClass');
$(row).addClass('removeClass'); //add class on clicked row
}
.visibilityHide {
display: none;
}
.highlightRow{
color:red;
}
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
/* styling for added class so that it looks something different when class added */
.removeClass{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTableid">
<thead>
<th>
col1header
</th>
<th>
col2header
</th>
</thead>
<tbody>
</tbody>
</table>
<input type="button" id ="addrows" value="add" onclick="add()" />
<input type="button" id="removerow" value="remove" onclick="remove()" class="visibilityHide" />
<br>
<br>
<br>
<div class="removed_row"></div>
You can check the answer in my update:
function remove()
{
window.selectedRow.remove();
$('#removerow').css('visibility', 'hidden');
}
function getdetails(row)
{
removeHighlights();
window.selectedRow = row;
row.classList.add("highlightRow");
$('#removerow').css('visibility', 'visible');
}
function removeHighlights() {
var elements = document.getElementsByClassName("highlightRow");
while(elements.length > 0){
elements[0].classList.remove('highlightRow');
}
}
https://jsfiddle.net/g63zpuuz/

Execute actions on a html element added with javascript

I am adding an element to an html page using javascript when a button is clicked and making an onclick attribute on this button to alert something as a test to make it execute something but it is not alerting anything when this added button is clicked. Here is the codes.
HTML
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
}
</style>
</head>
<body>
<div style="display:inline-flex;">
<input id="inptext" type="text" placeholder="Your name..."></input>
<input id="inpadress" style="margin-left: 10px;" id="inptext" type="text" placeholder="Your email..."></input>
<button onclick="myFunction()"style="margin-left: 10px;" id="box">Add</button>
</div>
<br>
<div style="display: inline-flex">
<table id="tablename" style="width:80%; margin-top:15px;">
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</table>
<div id="buttons" style="float:right;width: 300px; margin-top:50px;">
</div>
</div>
<script>
var z = 1;
function myFunction() {
var x = document.getElementById("inptext").value;
var y = document.getElementById("inpadress").value;
document.getElementById("tablename").innerHTML = document.getElementById("tablename").innerHTML + '<tr><td>' + x + '</td><td>' + y + '</td></tr>';
document.getElementById("buttons").innerHTML = document.getElementById("buttons").innerHTML + '<button onclick="myFunctionedit()" style="margin-left:8px" class="edit" id="vda' + z + '">Edit</button><button onclick="window.alert("sometext");" style="margin-left:4px" class="deleteit" id="a' + z + '">Remove</button><button style="margin-left:8px" class="update" id="cvda' + z + '">Update</button></div><div id="zzza' + z + '" style="height:10px"></div>';
document.getElementById('cvda'+z).style.visibility = 'hidden';
z = z+1;
}
</script>
</body>
</html>
Inside the alert you are using double quotes:
<button onclick="window.alert("sometext");" style="margin-left:4px" class="deleteit" id="a' + z + '">
Try changing it to single quotes:
<button onclick="window.alert(\'sometext\');" style="margin-left:4px" class="deleteit" id="a' + z + '">
<button onclick="window.alert("sometext");" style="margin-left:4px" class="deleteit" id="a' + z + '">Remove</button>
makes for invalid html.
Try
<button onclick="window.alert(\'sometext\');" style="margin-left:4px" class="deleteit" id="a' + z + '">Remove</button>
On top of that, the float: right; in #buttons is making the buttons unclickable. You can either remove that float or give it a z-index.
Working JSFiddle: https://jsfiddle.net/L8ymqLwh/ (with float: right; removed)

Convert an particular TD element of a table to Select with pre-populated Options

I am very new to jQuery,so bear with me if it seems to be silly question.
I have an table with many TD's in each row.I need to convert an TD element with plain text belonging to a particular column into an TD with Select element with pre-populated options,when user clicks that TD of that column using jQuery.
You can't convert the td into a select, because that would result in an invalid document. What you can do, is put the select within the td. E.g.:
$('selector for the td in question').html(
'<select>' +
'<option value="1">One</option>' +
'<option value="2">Two</option>' +
'<option value="3">Three</option>' +
'</select>'
);
Here's a complete example, also demonstrating event delegation: Live Copy
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<meta charset=utf-8 />
<title>Select in Cell</title>
<style>
.type {
cursor: pointer;
white-space: nowrap;
}
table {
border: 1px solid #aaa;
border-collapse: collapse;
}
td, th {
border: 1px solid #aaa;
padding: 2px;
}
</style>
</head>
<body>
<p>Click cells in the type column.</p>
<table id="theTable">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="type">Thingy</td>
<td>Blah</td>
</tr>
<tr>
<td class="type">Widget</td>
<td>Blah</td>
</tr>
<tr>
<td class="type">Whatsit</td>
<td>Blah</td>
</tr>
</tbody>
</table>
<script>
(function() {
$("#theTable").on("click", ".type", function() {
var $this = $(this),
current = $this.text(),
select;
if ($this.find("select").length) {
return;
}
select = $(
'<select>' +
'<option>Thingy</option>' +
'<option>Widget</option>' +
'<option>Whatsit</option>' +
'</select>'
);
$this.html(select);
select.val(current).focus();
});
$("#theTable").on("blur", ".type select", function() {
var $this = $(this);
$this.closest('td').text($this.val());
});
})();
</script>
</body>
</html>
Interesting task. Try this solution:
$('table').on('click', 'td', function(e) {
if ($(this).data('converted')) {
e.stopPropagation();
return;
}
$(this).data('converted', $(this).text());
var rowIndex = this.parentNode.rowIndex,
index = this.cellIndex + 1,
options = $(e.delegateTarget).find('td:nth-child(' + index +')').map(function(i) {
var text = $(this).data('converted') || $(this).text();
return '<option ' + (rowIndex == i ? 'selected' : '') + '>' + text + '</option>';
}).get();
$(this).html('<select>' + options.join('') + '</select>');
});
Demo: http://jsfiddle.net/As9dY/2/
Q: How to add a select dropdown to a TD dynamically?
Here's how you do it:
HTML:
<table>
<tr><th>Column A</th><th>Column B</th></tr>
<tr><td>1</td><td>6</td></tr>
<tr><td>2</td><td>7</td></tr>
<tr><td>3</td><td>8</td></tr>
<tr><td>4</td><td id="nine">9</td></tr>
<tr><td>5</td><td>10</td></tr>
</table>
jQuery:
$(document).ready(function() {
var isAppended = false;
var select = "<select name='mySelect'>" +
"<option value='volvo'>Volvo</option>" +
"<option value='saab'>Saab</option>" +
"<option value='opel'>Opel</option>" +
"<option value='audi'>Audi</option>" +
"</select>";
$("#nine").click(function() {
if (!isAppended) {
$(this).append(select);
isAppended = true;
}
});
});
JSFIDDLE DEMO

Categories

Resources