How to delete dynamically added row using jQuery? - javascript

I am trying to put a 'Delete' button after each of the row of my table.The delete button should function in such a way that it should only get activated when a new row is added. And if out of two rows one row is deleted the delete button of the existing row should also get deactivated.Any help will be appreciated. Thanks.
var regex = /^([a-zA-Z0-9 _-]+)$/;
var cindex = 0;
$(document).on('click','.Buttons', function(e) {
var count = $('table tr:last input:text').filter((_,el) => el.value.trim() == "").length;
if(count || !$('select:last').val()){
alert("Please fill all the fields in the current row");
return false;
}
var $tr = $('#dataTable tbody tr:last');
var $clone = $tr.clone(true);
cindex++;
$clone.find(':input').not('select').val('').attr('disabled', true);
$clone.attr('id', 'id'+(cindex) ); //update row id if required
//update ids of elements in row
$clone.find("*").each(function() {
var id = this.id || "";
if(id != ""){
var match = id.match(regex) || [];
if (match.length == 2) {
this.id = match[1] + (cindex);
}
}
});
$tr.after($clone);
});
/*`For delete button*/
$(document).on("click", '.DeleteButton', function() {
$(this).closest("tr").remove();
});
/*for enable field*/
$(document).on("click", '.DeleteButton', function() {
$(this).closest("tr").remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="0" cellspacing="1" cellpadding="1" id="dataTable" class="graphtable">
<thead>
<tr>
<td class="headingalign" width="16%">Links</td>
<td class="headingalign" width="32%">Desciption</td>
<td class="headingalign" width="16%">Image</td>
<td class="headingalign" width="16%">URL</td>
<td class="headingalign" width="16%"></td>
</tr>
</thead>
<tbody>
<tr id="id01" name="row">
<td>
<select type="select-one" id='fldsearch' class="objselect" name="fldsearch" onChange="disableField()" >
<option value="">Select</option>
<option value="GDS">Guides</option>
<option value="LOF">Latest Offers</option>
<option value="TEM">Templates</option>
<option value="VID">Videos</option>
</select>
</td>
<td>
<input id="flddesc" name="flddesc" maxlength="500" disabled="true" class="objinputtext" size="85" value="{//RESPONSE}" />
</td>
<td>
<input id="fldimg" name="fldimg" maxlength="50" disabled="true" class="objinputtext" size="35" value="{//RESPONSE}" />
</td>
<td>
<input id="fldurl" name="fldurl" maxlength="15" disabled="true" class="objinputtext" size="35" value="{//RESPONSE}" />
</td>
<td>
<input tabindex="6" id="Button4" value="Delete Row" disabled="true" class="DeleteButton" name="Button4" type="button" />
</td>
</tr>
</tbody>
</table>
<div class="buttonarea">
<ul>
<li><input tabindex="6" id="Button3" value="Add New Row" class="Buttons" name="Button3" type="button" /></li>
</ul>
</div>

You can get the count of rows in the table on every 'Add New Row' button and 'Delete Row' button click by:
var Count = $('#dataTable tr').length;
Then using the value of Count you can enable/disable the delete button e.g
if(Count < 2 )
//code to disable
else
//code to enable

I don't know if I get your question right, but I would try to do it like so:
I would handle this over a class namend 'active'. You also can give this class a disabled style. Also I would toggle the show/hide function of jquery if the button was clicked. And if one button is the last man standing - I would hide all. So it cant be clicked anymore. You can also ignore the 'active'-Class if you juste need to show/hide the buttons. The buttons should have a specific class 'del-btn'.
Note: Class 'active' is just for showing the button but disable/enable. Show/hide is for 'removing' the button.
var regex = /^([a-zA-Z0-9 _-]+)$/;
var cindex = 0;
$(document).on('click','.Buttons', function(e) {
var count = $('table tr:last input:text').filter((_,el) => el.value.trim() == "").length;
if(count || !$('select:last').val()){
alert("Please fill all the fields in the current row");
return false;
}
var $tr = $('#dataTable tbody tr:last');
var $clone = $tr.clone(true);
cindex++;
$clone.find(':input').not('select').val('').attr('disabled', true);
$clone.attr('id', 'id'+(cindex) ); //update row id if required
//update ids of elements in row
$clone.find("*").each(function() {
var id = this.id || "";
if(id != ""){
var match = id.match(regex) || [];
if (match.length == 2) {
this.id = match[1] + (cindex);
}
}
});
// If you want to activate ALL buttons:
$('.del-btn').addClass('active');
// If just the added row should be active:
$clone.find('.del-btn').addClass('active');
$(".del-btn").show();
$tr.after($clone);
});
/*`For delete button*/
$(document).on("click", '.DeleteButton', function() {
if(!$(this).hasClass('active')){
// removing is allowed
$(this).closest("tr").remove();
// Now you can check, if the rest should be shown or not
var btns = $('.del-btn').length; // count the buttons in the dom
if(btns>0){
if(btns == 1){
$(".del-btn").hide();
}else{
$(".del-btn").show();
}
}
}else{
// removing is disallowed
}
});
``````````````````````````for enable field``````````````````````
$(document).on("click", '.DeleteButton', function() {
$(this).closest("tr").remove();
});

Related

Change table row ID dynamically when delete in jquery

html
<table class="table table-bordered listable">
<thead>
<tr class="text-center">
<th>name</th>
<th>amount</th>
<th style="text-align:center">
+
</th>
</tr>
</thead>
<tbody class="text-center">
<tr class="cb" id="row_0">
<td width="20%">
<select class="form-control select2 firstname v1" id="name1_0" name="name[]" style="width: 100%;">
<option id="1">tan</option><option id="2">lim</option>
</select></td>
<td width="20%"><input type="number" name="winlose[]" id="amt1_0" class="form-control first"></td>
<td width="20%">-</td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-primary savebtn">Save</button>
Jquery
$('.addRow').on('click', function(){
addRow();
});
function addRow()
{
var rowCount = $('.listable tr').length -1;
var tr = '<tr class="cb" id="row_'+rowCount+'"><td>';
tr += '<select class="form-control select2" id="name1_'+rowCount+' first" name="name[]">';
tr += '<option id="1">tan</option><option id="2">lim</option></select></td>';
tr += '<td><input type="number" name="winlose[]" id="amt1_'+rowCount+'" class="form-control"></td>';
tr += '<td style="text-align:center">-';
tr += '</td></tr>';
i++;
$('tbody').append(tr);
}
$('tbody').on('click', '.remove', function(){
$(this).parent().parent().remove();
});
$('.savebtn').on('click', function(){
$('.listable .cb').each(function(index, item){
console.log($('#amt1_'+index).val());
});
});
https://jsfiddle.net/u3hmfc7x/1/
This will dynamically add table rows or delete the row when I click the button. After that, if user deleting the second row, then the row id 2 has been deleted and row id should be interchanged dynamically. Does anyone know how to fix this :(?
For example
<tr class="cb" id="row_0"><td>a</td></tr>
<tr class="cb" id="row_1"><td>b</td></tr>
<tr class="cb" id="row_2"><td>c</td></tr>
If user delete the second, the rest will auto sequence back the ID, it will become as below
<tr class="cb" id="row_0"><td>a</td></tr>
<tr class="cb" id="row_1"><td>c</td></tr>
you don't need the id to get values from input elements, we can easily get value of each input dynamically, check below code.
$('.savebtn').on('click', function(){
$('.listable .cb').each(function(index, item){
console.log($(item).find('input[type=number]').val());
});
});
https://jsfiddle.net/n7dzhwk4/
I think a wiser option, instead of changing the ID, would be to swap the values. You can do that by changing your onclick for delete operation to:
$('tbody').on('click', '.remove', function(){
elements = $(".cb");
current = parseInt($(this).id);
for (let itr = current; itr < elements.length - 1; itr++) {
elements[itr].value = elements[itr + 1].value;
}
elements[elements.length - 1].remove();
i--;
});
Here's the code for that: https://jsfiddle.net/ckpLqs4g/
try this,
actually this is not the best method to solve this, you really dont need to change the id dynamically but i hope this will help you
$('.addRow').on('click', function(){
addRow();
});
function addRow()
{
var rowCount = $('.listable tr').length -1;
var tr = '<tr class="cb" id="row_'+rowCount+'"><td>';
tr += '<select class="form-control select2" id="name1_'+rowCount+' first" name="name[]">';
tr += '<option id="1">tan</option><option id="2">lim</option></select></td>';
tr += '<td><input type="number" name="winlose[]" id="amt1_'+rowCount+'" class="form-control"></td>';
tr += '<td style="text-align:center">-';
tr += '</td></tr>';
i++;
let elementCount = 0
$('tbody').append(tr);
$('tbody').children('tr').each(function () {
this.attr('id',`row_${elementCount}`);
elementCount++;
});
}
$('tbody').on('click', '.remove', function(){
$(this).parent().parent().remove();
});
$('.savebtn').on('click', function(){
$('.listable .cb').each(function(index, item){
console.log($('#amt1_'+index).val());
});
});

How to enable disabled fields using jQuery?

function disableField()
{
var Count = $('#dataTable tr').length;
if (Count == 2){
$("input").not('.DeleteButton').prop('disabled', false);
}else{
$("input").prop('disabled', false);
}
}
//--------------------------------------------------
var regex = /^([a-zA-Z0-9 _-]+)$/;
var cindex = 0;
var quicklink = '' ;
$(document).on('click','.Buttons', function(addrow) {
var count = $('table tr:last input:text').filter((_,el) => el.value.trim() == "").length;
if(count || !$('.id_100 option[value=code]').attr('selected','selected')){
alert("Please fill the current row");
return false;
}
var $tr = $('#dataTable tbody tr:last');
var $clone = $tr.clone(true);
cindex++;
$clone.find(':input').not('select').not('.DeleteButton').val('').attr('disabled', true);
$clone.attr('id', 'id'+(cindex) ); //update row id if required
//update ids of elements in row
$clone.find("*").each(function() {
var id = this.id || "";
if(id != ""){
var match = id.match(regex) || [];
if (match.length == 2) {
this.id = this.name + (cindex);
}
}
});
$tr.after($clone);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table cellspacing="0" cellpadding="0" border="0" id="mainbox" class="mainbox"><tr><td>
<div class="toppanel"><ul><li></li></ul></div>
<div class="abcd"> <!--mainbox middlepanel start-->
<table cellspacing="0" cellpadding="0" border="0" id="maintable" class="maintable">
<tr>
<td valign="top">
<div id="pageheadingpanel">
<div id="pageheading">Quick Link Widget Configuration</div>
<div id="pageheadingdate"><xsl:call-template name="formatted_date"/></div>
</div>
</td>
</tr>
<tr>
<td height="100%" valign="top">
<div class="y_scroll" id="contentarea">
<div class="contentarea"><!--contentarea start-->
<span id="box" class="box"> <!--rounded curve/border start-->
<div class="middlepanel"> <!--contentarea box middlepanel start-->
<div style="display:block" id="textBox1" >
<span id="box1" class="box">
<div class="toppanel"><ul><li></li></ul></div>
<div class="middlepanel">
<table border="0" cellspacing="1" cellpadding="1" id="dataTable" name="dataTable" class="graphtable">
<thead>
<tr>
<td class="headingalign" width="16%">Links</td>
<td class="headingalign" width="32%">Desciption</td>
<td class="headingalign" width="16%">Image</td>
<td class="headingalign" width="16%">URL</td>
<td class="headingalign" width="05%"></td>
</tr>
</thead>
<tbody>
<tr id="id0" class="vals" name="id0">
<td>
<div class="id_100">
<select type="select-one" id='fldsearch' class="objselect" name="fldsearch" onChange="disableField()" >
<option value="">Select</option>
<xsl:for-each select="values from local db">
<xsl:sort order="ascending" select="description"/>
<option value="{description}">
<xsl:value-of select="description"/>
</option>
</xsl:for-each>
</select>
</div> </td>
<td>
<input id="flddesc" name="flddesc" maxlength="500" disabled="true" class="objinputtext1" size="85" value="{//RESPONSE}" />
</td>
<td>
<input id="fldimg" name="fldimg" maxlength="50" disabled="true" class="objinputtext2" size="35" value="{//RESPONSE}" />
</td>
<td>
<input id="fldurl" name="fldurl" maxlength="15" disabled="true" class="objinputtext3" size="35" value="{//RESPONSE}" />
</td>
<td>
<input tabindex="6" value="Delete Row" disabled="true" class="DeleteButton" type="button" />
</td>
</tr>
</tbody>
</table>
<div class="buttonarea">
<ul>
<li><input tabindex="6" id="Button3" value="Add New Row" class="Buttons" name="Button3" type="button" /></li>
</ul>
</div>
I have a table with a drop-down column in it. Whenever i change the values of drop-down my corresponding fields get enabled. The problem i am getting is if i change the values of my drop-down of previous row the columns of current row also get enabled.Any help will be appreciated. Thanks.
Edit:I have added 'Add Row' function too in my code.
I have added some changes in your disableField function. Pass parameter(this) disableField(this) in that function on chnage event.
function disableField(elem)
{
var Count = $('#dataTable tr').length;
if (Count == 2){
$(elem).closest('tr').find("input").not('.DeleteButton').prop('disabled', false);
}
else{
$(elem).closest('tr').find("input").prop('disabled', false);
}}
//--------------------------------------------------
var regex = /^([a-zA-Z0-9 _-]+)$/;
var cindex = 0;
var quicklink = '' ;
$(document).on('click','.Buttons', function(addrow) {
var count = $('table tr:last input:text').filter((_,el) => el.value.trim() == "").length;
if(count || !$('.id_100 option[value=code]').attr('selected','selected')){
alert("Please fill the current row");
return false;
}
var $tr = $('#dataTable tbody tr:last');
var $clone = $tr.clone(true);
cindex++;
$clone.find(':input').not('select').attr('disabled', true);
$clone.attr('id', 'id'+(cindex) ); //update row id if required
//update ids of elements in row
$clone.find("*").each(function() {
var id = this.id || "";
if(id != ""){
var match = id.match(regex) || [];
if (match.length == 2) {
this.id = this.name + (cindex);
}
}
});
$tr.after($clone);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table cellspacing="0" cellpadding="0" border="0" id="mainbox" class="mainbox"><tr><td>
<div class="toppanel"><ul><li></li></ul></div>
<div class="abcd"> <!--mainbox middlepanel start-->
<table cellspacing="0" cellpadding="0" border="0" id="maintable" class="maintable">
<tr>
<td valign="top">
<div id="pageheadingpanel">
<div id="pageheading">Quick Link Widget Configuration</div>
<div id="pageheadingdate"><xsl:call-template name="formatted_date"/></div>
</div>
</td>
</tr>
<tr>
<td height="100%" valign="top">
<div class="y_scroll" id="contentarea">
<div class="contentarea"><!--contentarea start-->
<span id="box" class="box"> <!--rounded curve/border start-->
<div class="middlepanel"> <!--contentarea box middlepanel start-->
<div style="display:block" id="textBox1" >
<span id="box1" class="box">
<div class="toppanel"><ul><li></li></ul></div>
<div class="middlepanel">
<table border="0" cellspacing="1" cellpadding="1" id="dataTable" name="dataTable" class="graphtable">
<thead>
<tr>
<td class="headingalign" width="16%">Links</td>
<td class="headingalign" width="32%">Desciption</td>
<td class="headingalign" width="16%">Image</td>
<td class="headingalign" width="16%">URL</td>
<td class="headingalign" width="05%"></td>
</tr>
</thead>
<tbody>
<tr id="id0" class="vals" name="id0">
<td>
<div class="id_100">
<select type="select-one" id='fldsearch' class="objselect" name="fldsearch" onChange="disableField(this)" >
<option value="">Select</option>
<xsl:for-each select="values from local db">
<xsl:sort order="ascending" select="description"/>
<option value="{description}">
<xsl:value-of select="description"/>
</option>
</xsl:for-each>
</select>
</div> </td>
<td>
<input id="flddesc" name="flddesc" maxlength="500" disabled="true" class="objinputtext1" size="85" value="{//RESPONSE}" />
</td>
<td>
<input id="fldimg" name="fldimg" maxlength="50" disabled="true" class="objinputtext2" size="35" value="{//RESPONSE}" />
</td>
<td>
<input id="fldurl" name="fldurl" maxlength="15" disabled="true" class="objinputtext3" size="35" value="{//RESPONSE}" />
</td>
<td>
<input tabindex="6" value="Delete Row" disabled="true" class="DeleteButton" type="button" />
</td>
</tr>
</tbody>
</table>
<div class="buttonarea">
<ul>
<li><input tabindex="6" id="Button3" value="Add New Row" class="Buttons" name="Button3" type="button" /></li>
</ul>
</div>
All in all there is to much extraneous code so the following answer has different code yet can be applied to the clunky code provided in question. I recommend that your code be more streamlined like the following demo provided in this answer.
Here's some suggestions:
If you are using multiple form controls (ex. <button>, <input>, <textarea>, <select>, etc), wrap everything into a <form>
If you have multiple tags (aka elements) that the user can click, submit, reset, change, input, etc register the events to the <form>
In order to find the exact form control that was clicked, changed, etc. use the Event.target property to find it or this keyword and the Event.data parameter.
$('form selector').on('event type', Event.data, callback function)
The #id and [name] attributes are unnecessary unless you are using certain Web APIs such as HTMLFormControlsCollection or HTMLFormElement
Never use event attributes (ex onchange="callback()") when using jQuery. Use the proper jQuery method or .on() method.
// jQuery method
$(selector).click(callback)
// .on() method
$(selector).on('click', callback)
Minor details:
The [type] attribute does not apply to the <select> tag.
Use <th> instead of <td> within <thead>
[maxlength] of 500 is ridiculous. Use <textarea> instead of <input>
Details are commented in demo
/*
Register form.io to the 'submit', 'click', and 'change' events
Note the callback function does not have `()` suffixed because it would be
interpreted as: "run function now"
The callback function doesn't run immediately it runs when a registered event is triggered.
*/
$('.io').on('submit click change', eventHandler);
// Define the counter
let counter = 0;
// Always pass the Event Object when defining a callback function
function eventHandler(event) {
// The Event Object has several properties...
// Get the type of event triggered (ie submit, change, or click)
let eType = event.type;
/*
Get the origin element of event
if 'submit' target will be <form>
if 'click' target will be <button>
if 'change' target will be <select>
*/
let eNode = event.target;
// Pass the event type through a switch() function...
switch (eType) {
// if type is 'submit'...
case 'submit':
// Create a deep clone of the first row
let clone = $('.grid tr:first-child').clone(true, true);
// Add clone as the last child of the <tbody>
$('.grid').append(clone);
// On .each() elment with class '.data' found within the clone...
clone.find('.data').each(function(i) {
// disable it
this.disabled = true;
// remove its value
this.value = '';
});
// Increment the counter by 1
counter++;
// Dereference the clone and assign id as row+counter
clone[0].id = `row${counter}`;
/*
Prevent default behavior:
Reset <form>
Send data to a server
*/
event.preventDefault();
// Stop event from bubbling any further up the event chain
event.stopPropagation();
// ...otherwise skip this case and continue onto the next case
break;
// if type is 'click'...
case 'click':
// if the clicked element (ie <button>) has class: '.del'...
if ($(eNode).hasClass('del')) {
// Get the clicked <button>'s ancestor <tr>
let row = $(eNode).closest('tr');
// if that <tr> is NOT the first <tr>...
if (row.index() !== 0) {
// remove the <tr>
row.remove();
}
}
event.stopPropagation();
break;
// if type is 'change'...
case 'change':
// if changed element (ie <select>) class is '.type'...
if ($(eNode).hasClass('type')) {
// Get the changed <select>'s ancestor <tr>
let row = $(eNode).closest('tr');
// if changed <select>'s value is NOT "X" return true otherwise return false
let pick = eNode.value !== "X" ? true : false;
/*
On .each() element with class .data within the <tr>
disable the .data if <select>'s value is "X"
Otherwise enable the .data
and then remove the .data value
*/
row.find('.data').each(function(i) {
this.disabled = !pick;
this.value = '';
});
}
event.stopPropagation();
break;
default:
event.stopPropagation();
break;
}
}
:root {
font: 400 3vw/1.2 Arial
}
form {
width: max-content;
margin: 10px auto
}
table {
table-layout: fixed;
border-collapse: separate;
border-spacing: 4px;
width: 90vw
}
th:first-of-type {
width: 20%
}
th:nth-of-type(2) {
width: 35%
}
th:nth-of-type(3) {
width: 35%
}
th:last-of-type {
width: 10%
}
td {
padding: 0 8px
}
select,
textarea,
button {
display: block;
min-width: 97%;
min-height: 1.2rem;
font-size: initial;
}
select {
padding: 2px 0 2px 2px
}
textarea {
resize: vertical;
overflow-y: auto;
overflow-x: hidden
}
<form class='io'>
<table>
<thead>
<tr>
<th>Type</th>
<th>Desciption</th>
<th>Image/URL</th>
<th><button>➕</button></th>
</tr>
</thead>
<tbody class='grid'>
<tr>
<td>
<select class='type'>
<option value="X" default></option>
<option value="GDS">Guides</option>
<option value="PRO">Promos</option>
<option value="TEM">Templates</option>
<option value="VID">Videos</option>
</select>
</td>
<td><textarea class='desc data' rows='1' cols='20' disabled></textarea></td>
<td><textarea class='urls data' rows='1' cols='20' disabled></textarea></td>
<td><button class='del' type='button'>❌</button></td>
</tr>
</tbody>
</table>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

HTML jquery: onclick function to delete dynamic table row is not calling

I just want to delete dynamically created row, but iam unable to call the function using jquery and javascript.
const dynamic_JS = ({ sno, optionVal, price }) => `<tr><td>${sno}</td> <td><select name="selectProduct" class="form-control" selected="${optionVal}"><option value="0"> -- Select One --</option><option value="1"> IPhone </option><option value="2"> MAC </option><option value="3"> Windows </option></select></td> <td><input type="text" class="form-control" value="${price}" title="" ></td> <td><button type="button" class="remove-row btn btn-info glyphicon glyphicon-remove" ></button></td> </tr>`;
// onclick=\'removeRow(this)\'
//window.onload=function(){}
$(document).ready(function() {
var template_add = $('#hidden-template').text();
function render(props) {
return function(tok, i) {
return (i % 2) ? props[tok] : tok;
};
}
var items = [ { sno: '1', optionVal: '0', price: '0' } ];
var dynamic_HTML = template_add.split(/\$\{(.+?)\}/g);
$('tbody').append(items.map(function(item) {
return dynamic_HTML.map(render(item)).join('');
}));
});
// https://stackoverflow.com/a/35592412/5081877
$('#number_only').on('input propertychange', function() {
this.value = this.value.replace(/[^0-9]/g, '');
});
$('.add-new').on('click', function () {
$("#productTable").each(function () {
var tr_last = $('tbody > tr:last', this).clone();
var td_no = tr_last.find('td:first');
var serialNumber = parseInt(td_no.text()) + 1;
// https://stackoverflow.com/a/6588327/5081877
var tr_first_input = $('tbody > tr:first > td:nth-child(3) > input');
var tr_first_price = parseFloat(tr_first_input.val()) || 0;
console.dir( tr_first_price );
totalamount += tr_first_price;
$('#totalAdd').text(totalamount);
var tr_first_selected = $('tbody > tr:first > td:nth-child(2) > select option').filter(":selected");
// option:selected | .find(":selected") ~ .text(), ~.attr('value');
var selectedValue = tr_first_selected.val(), optionText = tr_first_selected.text().trim();
console.log(' Text : ', optionText );
console.log('Value : ', selectedValue );
// https://stackoverflow.com/a/39065147/5081877
$('tbody', this).append([
{ sno: serialNumber, optionVal: selectedValue, price: tr_first_price }
].map(dynamic_JS).join(''));
var last_optionSel = $('tbody#mainBody > tr:last > td:nth-child(2) > select');
last_optionSel.val( selectedValue );
tr_first_input.val( 0 );
// https://stackoverflow.com/a/13089959/5081877
var first_optionSel = $('#productOption');
//$('tbody > tr:first > td:nth-child(2) > select ');
first_optionSel.val( 0 );
return;
});
});
var totalamount = 0; // tr#mainRow
$('table#productTable > tbody ').on('keyup', 'input', function(e) {
var total =
$(e.delegateTarget)
.find('input')
.map(function() {
return parseFloat($(this).val()) || 0;
})
.get()
.reduce(function(a, b) {
return a + b;
});
$('#total').text(total);
});
<!-- Remove row - javascript & Jquery -->
$('.remove-row').on('click', function () {
$("#productTable").each(function () {
// added total minus deleting element price.
$(this).closest('tr').remove();
});
});
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<body>
<table id="productTable" class="table table-hover table-bordered">
<thead>
<tr>
<th>No.</th><th>Product</th><th>Price</th><th>Action</th>
</tr>
</thead>
<tbody id="mainBody">
</tbody>
<tfoot>
<tr>
<td></td>
<td></td>
<td>
Expected Total:<span id="total">0</span><br>
Added Total:<span id="totalAdd">0</span>
</td>
<td></td>
</tr>
</tfoot>
</table>
<button type="button" class="add-new btn btn-info" id="add-new">Add New Income</button>
<script id="hidden-template" type="text/x-custom-template">
<tr id="mainRow">
<td>${sno}</td>
<td>
<select name="selectProduct" id="productOption" class="form-control" selected="${optionVal}">
<option value="0"> -- Select One --</option>
<option value="1"> IPhone </option>
<option value="2"> MAC </option>
<option value="3"> Windows </option>
</select>
</td>
<td>
<input id="number_only" pattern="[0-9]" type="text" class="form-control" />
</td>
<td><!-- glyphicon-plus | glyphicon-remove -->
<button type="button" class="add-new btn btn-info glyphicon glyphicon-plus"></button>
</td>
</tr>
</script>
</body>
Stackoverflow snippet - using javascript onclick function remove current row is working fine.
function removeRow(onclickTAG) {
// Iterate till we find TR tag.
while ( (onclickTAG = onclickTAG.parentElement) && onclickTAG.tagName != 'TR' );
onclickTAG.parentElement.removeChild(onclickTAG);
}
as part of jsfiddle - test and plane html file the code is not working at-least with javascript.
Unable to delete|call delete row function. while deleting row remove the price from the Added Total.
I should only allow number for the input tag, but it is working only for the first row input element. Input type must be text only. type number allows these like {.+-}
Iam unable to solve it as new to jquery and its xpath element navigation.
There are two issues with your code:
$('table#productTable:.remove-row').on('click', function () {
here :. is an syntax error, and it is showing in console.
Second to put an event listener on dynamic html, you have to use $(document).on() like:
$(document).on('click', '.remove-row', function(){
Check the updated working fiddle
here
I have added events using on click event handler as elements get added dynamically.
Have updated both events:
1. Event for remove button
$('table#productTable').on('click', '.remove-row', function() {
//$("#productTable").each(function () {
// added total minus deleting element price.
$(this).closest('tr').remove(); // https://stackoverflow.com/a/11553788/5081877
//$(element).parent().remove();
//});
});
2. Event for input tag
$('table#productTable').on('input propertychange',' > tbody > tr > td:nth-child(3) > input', function() {
$.each($('input[type=text]'), function() {
this.value = this.value.replace(/[^0-9]/g, '');
});
});
Refer this fiddle
Please change $('.row).onclick like this
$('table#productTable').on('click', '.remove-row', function()
And remove this $("#productTable").each(function () {

Search box for table

Given this table:
<table class="tbllist searchtbl" cellpadding=2 cellspacing=0 style="width: 70%">
<tr>
<th class="hidden">ID</th>
<th>Number Plate</th>
<th>Chassis Number</th>
<th>Trailer Make</th>
<th>Year</th>
<th>Axles</th>
<th></th>
</tr>
<tr class='tbl'>
<td class='hidden'>3</td>
<td>
<input type=text style = 'width: 75px' class='centered' id='trnumberplate_3' name='trnumberplate_3' value='T212ABS' onfocus='this.oldvalue = this.value;' onchange='updatevalue("trailers","trnumberplate", this.value ,"trid","3","","1",this, "false")'>
</td>
<td>
<input type=text style = 'width: 200px' id='trchassisnumber_3' name='trchassisnumber_3' value='AJSDGASJH' onfocus='this.oldvalue = this.value;' onchange='updatevalue("trailers","trchassisnumber", this.value ,"trid","3","","1",this, "false")'>
</td>
<td>
<input type=text style = 'width: 200px' id='trmake_3' name='trmake_3' value='LOW LOADER' onfocus='this.oldvalue = this.value;' onchange='updatevalue("trailers","trmake", this.value ,"trid","3","","1",this, "false")'>
</td>
<td>
<input type=text style = 'width: 50px' class='centered' id='tryear_3' name='tryear_3' value='2009' onfocus='this.oldvalue = this.value;' onchange='updatevalue("trailers","tryear", this.value ,"trid","3","1","",this, "false")'>
</td>
<td>
<input type=text style = 'width: 25px' class='centered' id='traxles_3' name='traxles_3' value='3' onfocus='this.oldvalue = this.value;' onchange='updatevalue("trailers","traxles", this.value ,"trid","3","1","",this, "false")'>
</td>
<td class='delbtn'>
<button id='trailers_3' title='DELETE THIS ITEM (3)?' onclick='event.preventDefault(); delitem("trailers","trid","3","trailers.php","#workspace")'><img src='/icons/delete.png' ></button>
</td>
</tr>
</table>
I have the following search function:
function searchbox() {
// text input search for tables (such as trip history etc)
$("#search").keyup(function () {
//split the current value of searchInput
var data = this.value.toUpperCase().split(" ");
//create a jquery object of the rows
var jo = $(".tbllist").find("tr").not("tr:first"); // exclude headers
if (this.value == "") {
jo.show();
return;
}
//hide all the rows
jo.hide();
//Recusively filter the jquery object to get results.
jo.filter(function (i, v) {
var $t = $(this);
for (var d = 0; d < data.length; ++d) {
if ($t.is(":contains('" + data[d] + "')")) {
return true;
}
}
return false;
})
//show the rows that match.
.show();
})
It will loop through table td's to check if the searched value is available and filter rows. It is not filtering if the td contains an input text element with the searched value.
Update:
if ($t.find("input").val().toUpperCase().indexOf(data[d]) > 0) {
return true;
}
Now works but will only matches the first column of the table.
JSFiddle: https://jsfiddle.net/fabriziomazzoni79/30d52c9z/
Change jo.filter() like this:
jo.filter(function (i, v) {
var txt = '';
$(v).find("input").each(function(n,e){
txt += e.value;
});
for(var d=0; d<data.length; d++){
if (txt.search(data[d])>=0) {
return true;
}
}
return false;
})
Fiddle here.

Changing input values from table1 to table2 on keypress mode

see FIDDLE DEMO
Can anyone guide me on keypress event, I can't get my input values right?
$(document).on('keydown', $('#table1 tbody tr td input'), function (e) {
var oldValue ='?';//get the input value before keypress or edit
var newValue = "?"; //get the input value after keypress or edit
$('#table2').find('tbody tr').each(function (i) {
var $td2 = $(this).find('td input:text');
if (oldValue == $td2.val()){
$td2.val(newValue);
}
});
});
and $(document).on('keydown', $('#table1 tbody tr td input'), function (e) { should only apply on table 1 first column ,right now it also applying when keypress on table1 column 2 is triggered.
Does if I edit "Apple" to "Apple Pie", Apple from table 2 will automatically change to "Apple Pie".
Try this:
$(document).off('keydown').on('keydown', $('#table1 tbody tr td input'), function (e) {
var oldValue =$(e.target).val();//get the input value before keypress or edit
$(document).on('keyup', $('#table1 tbody tr td input'),function(e){
$('#table2').find('td input').each(function(){
if($(this).val() === oldValue){
$(this).val($(e.target).val());
}
$(document).off('keyup');
});
});
});
Try this now:
$(document).off('keydown').on('keydown', '#table1 input:first', function (e) {
var oldValue =$(e.target).val();//get the input value before keypress or edit
$(document).on('keyup', '#table1 input:first',function(e){
$('#table2').find('td input:first').val($(e.target).val());
$(document).off('keyup');
});
});
here is fiddle
here is the snippet for better understand i have changed the event
Reason: if you wish to instant change
HTML CODE
<form id='form1'>
<table id='table1'>
<tbody>
<tr>
<td>
<input type='text' class="1" value="Apple" />
</td>
<td>
<input type='text' value="" />
</td>
</tr>
<tr>
<td>
<input type='text' class="2" value="Banana" />
</td>
<td>
<input type='text' value="" />
</td>
</tr>
</tbody>
</table>Table2
<table id='table2'>
<tbody>
<tr>
<td>
<input type='text' class="1" value="Apple" />
</td>
</tr>
<tr>
<td>
<input type='text' class="2" value="Banana" />
</td>
</tr>
<tr>
<td>
<input type='text' class="3" value="Banana" />
</td>
</tr>
</tbody>
</table>
<br />
JAVASCRIPT CODE
$(document).on('keyup', '#table1 tbody tr td input', function (e) {
var cls = $(this).attr('class');
var oldValue ='?';//get the input value before keypress or edit
var newValue = "?"; //get the input value after keypress or edit
newValue = $(this).val();
$('#table2').find('tbody tr').each(function (i) {
var targInp = $(this).find('td input.'+cls)//$(this).find('td input:text')hasClass(cls);
oldValue = $(this).find('td input.'+cls).val();
console.log('got it', oldValue);
if (oldValue != newValue){
targInp.val(newValue);
}
});
});

Categories