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>
Related
Here is how I am adding Bank names rows and the which will be added to it
How can i subtract from total row in real time > onkeyup > by creating input using jquery and putting value in it? please help. Actually I want my total sale to be deposited to different banks thats why I want it
<form method="GET" action="savebank.php" class="">
<table class="table table-bordered" id='TextBoxesGroup'>
<tr>
<th>Total Amount</th>
<th id="total" value="<?php echo $tsp; ?>">Rs. <?php echo $tsp; ?></th>
</tr>
<tr id="TextBoxDiv1">
<!-- INPUT BOXES WILL BE HERE-->
</tr>
</table>
<button type="submit" class="btn btn-lg btn-success btn-block" id="ttwo" style="display:none;">Submit</button>
</form>
<!-- Below is jquery -->
<script type="text/javascript">
$(document).ready(function() {
var counter = 2;
$("#addmore").click(function() {
if (counter > 30) {
alert("No more textboxes allowed");
return false;
}
var newTextBoxDiv = $(document.createElement('tr'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<td><input type="text" name="bank[]" required class="form-control" placeholder="Bank Name" id="textbox' + counter + '"></td>' +
'<td><input type="number" name="amnt[]" required class="form-control textboz" placeholder="Amount" id="textbox' + counter + '"></td>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("ttwo").css("display", "block");
$("#remove").click(function() {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function() {
var msg = '';
for (i = 1; i < counter; i++) {
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
I want to build tables that fetch data from api and I succeeded in that so I need now to calculate numbers of table rows and show total in next row or in span div it does not matter. I just need total as shown in image..
I already tried many solutions to calculate rows but always get result zero or NaN. I'm not sure what I'm doing wrong or maybe I just made mistake somewhere in this code... I would appreciate your opinion or solution if possible.
function statsYesterday() {
$.getJSON('https://api.url, function(data) {
var data, i, offer, creative, id, conversion, clicks, payout = "";
for (i in data.response.data.data) {
offer += "<table><tr><td>" + data.response.data.data[i].Offer.name + "</td></tr></table>";
creative += "<table><tr><td>" + data.response.data.data[i].OfferUrl.name + "</td></tr></table>";
id += "<table><tr><td>" + data.response.data.data[i].Stat.affiliate_info1 + "</td></tr></table>";
conversion += "<table><tr><td>" + data.response.data.data[i].Stat.conversions + "</td></tr></table>";
clicks += "<table><tr><td>" + data.response.data.data[i].Stat.clicks + "</td></tr></table>";
//this code reduce payout by 20%
var num = parseFloat(data.response.data.data[i].Stat.payout);
var val = num - (num * .20);
payout += "<table><tr><td> € " + val + "</td></tr></table>";
});
//end reduce code
//this is how code look like without reducing percentage
//payout += "<table><tr><td>" + data.response.data.data[i].Stat.payout + "</td></tr></table>";
document.getElementById("offer_name").innerHTML = offer;
document.getElementById("creative_name").innerHTML = creative;
document.getElementById("id_name").innerHTML = id;
document.getElementById("converion_name").innerHTML = conversion;
document.getElementById("clicks_name").innerHTML = clicks;
document.getElementById("payout_name").innerHTML = payout;
};
});
};
<body>
<div class="container">
<br><br><button onclick="statsYesterday()" style="background-color: #4CAF50;border: none;color: white;padding: 16px 32px;text-align: center;text-decoration: none;display: inline-block;font-size: 16px;margin: 4px 2px;transition-duration: 0.4s;cursor: pointer;">Yesterday</button> <button onclick="statsToday()" style="background-color: #4CAF50;border: none;color: white;padding: 16px 32px;text-align: center;text-decoration: none;display: inline-block;font-size: 16px;margin: 4px 2px;transition-duration: 0.4s;cursor: pointer;">Today</button> <button onclick="statsLastWeek()" style="background-color: #4CAF50;border: none;color: white;padding: 16px 32px;text-align: center;text-decoration: none;display: inline-block;font-size: 16px;margin: 4px 2px;transition-duration: 0.4s;cursor: pointer;">Last Week</button>
<br><br>
<table class="table" id="table">
<thead>
<tr>
<th>Offer</th>
<th>Creative</th>
<th>SubID</th>
<th>Conversion</th>
<th>Clicks</th>
<th>Payout</th>
</tr>
</thead>
<tbody>
<tr>
<td id="offer_name"></td>
<td id="creative_name"></td>
<td id="id_name"></td>
<td id="converion_name"></td>
<td id="clicks_name"></td>
<td id="payout_name" style="padding-top:30px;"></td>
</tr>
</tbody>
</table>
<br><br>
</div>
</body>
push the values into an array and then you can perform an addition on them later
something like this
values=[]
//... your code
var num = parseFloat(data.response.data.data[i].Stat.payout);
var val = num - (num * .20);
values.push(val)
and then later you can simply iterate over the array and add the values
let total=values.reduce((acc,curr)=>acc+curr)
document.getElementById("total").textContent=total
There is 3 issues in my code:
Infinite while loop I dont understand why, I'm just trying to test if the prompt is a number or not (If not -> Prompt again until it is) [SOLVED]
If min/max are correct, they should be added to all the cells from that column
From :
<input type=text...
To :
<input type=number min=... max=...
Currently, they are not even added and the type is indeed converted to number but for the full table, not for that specific column, which is not what I want obviously
What I want is to, when I press that "nbr" button from that specific column, convert all the cells' type from that column from text to nbr (and add min and max values to it) [SOLVED]
When I press that "nbr" button, it changes all the input fields from all the tables from text fields into number fields. What I'm trying to do is only changing the text fields from that column into "nbr" fields, only that column. [SOLVED]
This is the part that doesn't work as intended :
//change column type to number
$('body').on('click', '.nbr-col', function(event) {
// ...
// Here I'm trying to add the min attribute to all the number fields from that specific column
$('input[type=\'number\']', event.delegateTarget).prop('min',($('#min').val()));
// Here I'm trying to add the max attribute to all the number fields from that specific column
$('input[type=\'number\']', event.delegateTarget).prop('max',($('#max').val()));
// Here I'm trying to convert all the text fields to number fields for that specific column (it kinda works, but it converts all the text fields from all the table to number fields, that's not what I want to do
$('input', event.delegateTarget).prop('type','number');
});
So the result should be (for example) :
Create as much columns and rows as I want
Press the "nbr" button from column 2
Should convert all the text fields from column 2 into number fields :
Convert this :
<td><input type="text" class="form-control"></td>
To this :
<td><input type='number' min=value_from_prompt max=value_from_prompt class="form-control"></td>
For each cells from column 2
Here is a picture :
nbr press converting all the into "number" from all the table, not only the column in question
Here's a full code fiddle: https://jsfiddle.net/wh9y05qt/
Here's my full code snippet :
// Code goes here
$(document).ready(function() {
// add row
$('body').on('click', '.add-row', function() {
var tr = $(this).parents('.table-content').find('.table tbody tr:last');
if (tr.length > 0) {
var clone = tr.clone();
clone.find(':text').val('');
tr.after(clone);
} else {
var cols = $(this).closest('.table-content').find('th').length,
tr0 = $('<tr/>');
tr0.html('<td><span class="remove remove-row">x</span></td><td> <input type="text" class="form-control"> </td>');
for (var i = 2; i < cols; i++) {
tr0.append('<td> static element </td>')
}
$(this).closest('.table-content').find('.table tbody').append(tr0);
//$(this).closest('.table-content').find('.table tbody').append('<tr> <td><span class="remove remove-row">x</span></td><td> <input type="text" class="form-control"> </td><td> static element </td><td> static element </td></tr>');
}
});
// delete row
$('body').on('click', '.remove-row', function() {
$(this).parents('tr').remove();
});
// add column
$('body').on('click', '.add-col', function() {
$(this).parent().find('.table thead tr').append('<th><input type="text" class="form-control pull-left" value=""> <span class="pull-left remove remove-col">x</span> <span class="pull-left text text-col">text</span> <span class="pull-left nbr nbr-col">nbr</span> </th>');
$(this).parent().find('.table tbody tr').append('<td><input type="text" class="form-control"></td>');
});
// change column type to text
$('body').on('click', '.text-col', function(event) {
// Get index of parent TD among its siblings (add one for nth-child)
//var ndx = $(this).parent().index() + 1;
// Find all TD elements with the same index
$('input', event.delegateTarget).prop('type','text');
});
// change column type to number
$('body').on('click', '.nbr-col', function(event) {
// Get index of parent TD among its siblings (add one for nth-child)
//var ndx = $(this).parent().index() + 1;
// Find all TD elements with the same index
var filter = /^[0-9]*$/g;
var cond = false;
var min = prompt('Valeur minimum :');
while (cond == false)
{
if (min.match(filter))
{
cond = true;
}
else {
var min = prompt('Valeur minimum incorrect, réessayez :');
}
}
var cond = false;
var max = prompt('Valeur maximum :');
while (cond == false)
{
if (max.match(filter))
{
cond = true;
}
else {
var max = prompt('Valeur maximum incorrect, réessayez :');
}
}
$('input[type=\'number\']', event.delegateTarget).prop('min',($('#min').val()));
$('input[type=\'number\']', event.delegateTarget).prop('max',($('#max').val()));
$('input', event.delegateTarget).prop('type','number');
});
// remove column
$('body').on('click', '.remove-col', function(event) {
// Get index of parent TD among its siblings (add one for nth-child)
var ndx = $(this).parent().index() + 1;
// Find all TD elements with the same index
$('th', event.delegateTarget).remove(':nth-child(' + ndx + ')');
$('td', event.delegateTarget).remove(':nth-child(' + ndx + ')');
});
});
/* Styles go here */
.table-content {
padding: 20px;
}
.remove {
margin-left: 10px;
color: red;
}
.remove:hover {
cursor: pointer;
}
.text {
margin-left: 10px;
color: blue;
}
.text:hover {
cursor: pointer;
}
.nbr {
margin-left: 10px;
color: green;
}
.nbr:hover {
cursor: pointer;
}
.form-control {
width: 90px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-1.11.2.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<div class="table-content">
<button class="btn btn-link add-col">Add Column</button>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th></th>
<th>Define</th>
</tr>
</thead>
<tbody>
<tr>
<td><span class="remove remove-row">x</span></td>
<td>
<input type="text" class="form-control">
</td>
</tr>
</tbody>
</table>
</div>
<button class="btn btn-link add-row">Add row</button>
</div>
After reading this long question, that what you really want is to just select all inputs from second td of the table body and set min, max and type="number", if is this, then I think that what you need is:
$(".table tbody tr td:nth-child(3) input")
check below snippet, is it what you need?
$(document).ready(function() {
// add row
$('body').on('click', '.add-row', function() {
var tr = $(this).parents('.table-content').find('.table tbody tr:last');
if (tr.length > 0) {
var clone = tr.clone();
clone.find(':text').val('');
tr.after(clone);
} else {
var cols = $(this).closest('.table-content').find('th').length,
tr0 = $('<tr/>');
tr0.html('<td><span class="remove remove-row">x</span></td><td> <input type="text" class="form-control"> </td>');
for (var i = 2; i < cols; i++) {
tr0.append('<td> static element </td>')
}
$(this).closest('.table-content').find('.table tbody').append(tr0);
}
});
// delete row
$('body').on('click', '.remove-row', function() {
$(this).parents('tr').remove();
});
// add column
$('body').on('click', '.add-col', function() {
$(this).parent().find('.table thead tr').append('<th><input type="text" class="form-control pull-left" value=""> <span class="pull-left remove remove-col">x</span> <span class="pull-left text text-col">text</span> <span class="pull-left nbr nbr-col">nbr</span> </th>');
$(this).parent().find('.table tbody tr').append('<td><input type="text" class="form-control"></td>');
});
// change column type to text
$('body').on('click', '.text-col', function(event) {
$('input', event.delegateTarget).prop('type', 'text');
});
// change column type to number
$('body').on('click', '.nbr-col', function(event) {
var filter = /^[0-9]*$/g;
var cond = false;
var min = prompt('Valeur minimum :');
while (cond == false) {
if (min.match(filter)) {
cond = true;
} else {
var min = prompt('Valeur minimum incorrect, réessayez :');
}
}
var cond = false;
var max = prompt('Valeur maximum :');
while (cond == false) {
if (max.match(filter)) {
cond = true;
} else {
var max = prompt('Valeur maximum incorrect, réessayez :');
}
}
let colToModify = $(this).parent().index() + 1;
let inputsCol = $(".table tbody tr td:nth-child(" + colToModify + ") input")
inputsCol.attr("type", "number").prop("min", min).prop("max", max)
console.log("modified columns index: " + colToModify)
});
// remove column
$('body').on('click', '.remove-col', function(event) {
var ndx = $(this).parent().index() + 1;
$('th', event.delegateTarget).remove(':nth-child(' + ndx + ')');
$('td', event.delegateTarget).remove(':nth-child(' + ndx + ')');
});
});
/* Styles go here */
.table-content {
padding: 20px;
}
.remove {
margin-left: 10px;
color: red;
}
.remove:hover {
cursor: pointer;
}
.text {
margin-left: 10px;
color: blue;
}
.text:hover {
cursor: pointer;
}
.nbr {
margin-left: 10px;
color: green;
}
.nbr:hover {
cursor: pointer;
}
.form-control {
width: 90px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-1.11.2.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<div class="table-content">
<button class="btn btn-link add-col">Add Column</button>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th></th>
<th>Define</th>
</tr>
</thead>
<tbody>
<tr>
<td><span class="remove remove-row">x</span></td>
<td>
<input type="text" class="form-control">
</td>
</tr>
</tbody>
</table>
</div>
<button class="btn btn-link add-row">Add row</button>
</div>
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/
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();
}
});