Javascript/JQuery to add and delete table row by Id - javascript

I am trying to add and delete rows (by Id) to my table dynamically. The add button works fine but I am not sure why the delete button doesn't work (it's either deletes the last row or doesn't work). Any suggestion please?
Here is my table:
<table class="customFiltersTable" id="customFiltersTable">
<tbody>
</tbody>
</table>
The Javascript add button has this code inside:
filtersRow = filtersRow + 1;
var fType1 = $('<tr class="rowTableFilters" id="rowFilters'+filtersRow+'" name="rowFilters'+filtersRow+'"><td class="colFilters" id="colFilters'+column1+'" name="colFilters'+column1+'" width="480px" align="center"></td><td class="colFilters" id="colFilters'+column2+'" name="colFilters'+column2+'" width="480px" align="center"></td><td class="delButton" id="delButton" name="delButton" width="40px" align="center"><button type="button" class="btn btn-link" id="deleteFilter'+filtersRow+'" name="deleteFilter'+filtersRow+'" style="float: right;">Del</button></td></tr>');
$("#customFiltersTable").append(fType1).promise().done(function () {
$("#deleteFilter" + filtersRow).click(function(){
var row = document.getElementById("rowFilters"+filtersRow);
row.parentNode.removeChild(row);
});
});
Thanks!

Acquaint yourself with jQuery's event delegation, https://learn.jquery.com/events/event-delegation/. You'll learn that you can avoid attaching the delete click listener to every row you add, and instead attach that listener once to the table element:
$('#customFiltersTable').on('click', 'button', function () {
$(this).closest('tr').remove();
});

You're incrementing filtersRow; however your click function only gets evaluated at the time you press the button. In other words, this code:
function(){
var row = document.getElementById("rowFilters"+filtersRow);
row.parentNode.removeChild(row);
}
is executed on click and will run with whatever value of filtersRow you last incremented. You'll always be removing the last row.
Perhaps something like:
function () {
$(this).closest('tr').remove();
}
Sorry, this is compiled in my head.

To add row:
var tmp = '<tr id="4_r"><td>row4</td></tr>';
$('#myTable tbody').append(tmp);
To delete row have id="4_r":
var iddel = "4_r";
$('#myTable').closest('table').find('tbody > tr')
.each(function(){
var idr = this.id;
if(idr == iddel){
$(this).remove();
}
});

Related

Disable click fot td for particular column using Jquery

I have tried to use Jquery to click a table row to go to a new page. But my last column has a button. For which clicking on the edge takes it to a new page. Anyway to disable the td onclick for that column. I tried using onclick='event.stopPropagation();return false;' but that would disable the button too.
My Jquery code below.
$(".myTable").on("click", "td", function(){
var issueid = $(this).closest('tr').find("td:eq(2) input").val();
window.location = 'viewminissues.jsp?issue_id='+issueid;
});
This can be handled in two ways:
Try adding event.preventDefault() along with event.stopPropagation().
Add a disabled class on the td element manually and then handle further scenarios with hasClass('disabled') check.
The issue is because the click event from the button propagates up the DOM to the tr which then transfers the page.
To fix this you could call stopPropagation() within the button event handler:
$(".myTable").on("click", "td", function() {
var issueid = $(this).closest('tr').data('issue');
console.log('Transferring to: viewminissues.jsp?issue_id=' + issueid);
//window.location.assign('viewminissues.jsp?issue_id=' + issueid);
});
$('.myTable').on('click', 'button', function(e) {
e.stopPropagation();
console.log('Perform button action...');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="myTable">
<tr data-issue="1">
<td>Foo bar</td>
<td><button>Edit</button></td>
</tr>
<tr data-issue="2">
<td>Lorem ipsum</td>
<td><button>Edit</button></td>
</tr>
</table>
You can exclude the last <td> from the click() event using :not(:last) like this:
$(".myTable").on("click", "td:not(:last)", function() {
var issueid = $(this).closest('tr').find("td:eq(2) input").val();
window.location = 'viewminissues.jsp?issue_id=' + issueid;
});

Alert toggles every time when the input is changed

I have input and it toggles a function if it's been changed. I also have table that is created dynamically. And each row in table has an addButton. So, the problem is that this alert toggles so many times so I change the input, but I need to toggle it only once. How to deal with it?
$('.inputsearchform').bind('input', function() {
var addButton = $(".fa.fa-plus");
addButton.click(function() {
alert("test");
});
});
I don't need to add click event to this button, but I need to get onclick() event from it. But this code is only working way, that I found. By the way, I need to get this event only if button is clicked, not every time that I change input.
Question How to check onclick event on button, that appears dynmically, when the input changes?
I tried to add onclick event <i class="fa fa-plus" onclick="addButtonF()">
and in js file: function addButtonF(){
alert("test");
}
but I have an error addButtonF is not defined.
A start would be to define click outside of input handler to prevent multiple click handler calls at each click of addButton
So, the problem is that this alert toggles so many times so I change
the input, but I need to toggle it only once.
Not clear from Question which element needs to be toggled once, or which function should only be called once ?
addButton appears only if I write something in input. I need to use
alert only if I click on this button, not every time that I change
input.
Use event delegation to attach event to dynamically created elements having className .fa.fa-plus
$(".inputsearchform").bind("input", function() {
// create dynamic element
$("<table class='fa fa-plus'>")
.html("<tr><td>"
+ $(".fa.fa-plus").length
+ "</td></tr>"
).appendTo("body");
});
$(document).on("click", ".fa.fa-plus", function() {
alert("test");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="text" class="inputsearchform">
Substitute className for class which does not set className of element; use latest version of jQuery
$(".inputsearchform").bind("input", function() {
var div = document.getElementById("div");
var table = document.createElement("table");
div.appendChild(table);
var tr = document.createElement("tr");
table.appendChild(tr);
var td = tr.insertCell(0);
td.innerHTML = "test";
td.className = "try"
});
$(document).on("click", ".try", function() {
alert("test");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="text" class="inputsearchform">
<div id="div"></div>
jsfiddle https://jsfiddle.net/1x8ja6qe/2/

click event on a cell and not entire row - with FIDDLE

I am currently using this code for row click event in a bootstrap table
$('#myTable').bootstrapTable().on('click-row.bs.table', function (e, row, $element)
{
//....my operation
}
The problem is this triggers for the entire row and I want to be able to trigger it for a single cell.
Note I am using the arguments, row and $element
Here is the FIDDLE
$element is the entire row, you cannot know what cell have been clicked by this way,
bootstrap table do not have cell click event, so you need manually add click event on last cell and fill your needed vars yourself
$('#table').bootstrapTable({
data: data
}).on('click','td:last-child',function(){
var $t = $(this), $row = $t.parent(), i = $row.index(), row = data[i];
var $firstTd = $row.children().eq(0);
if($firstTd.data("haveTable") !== true){
$firstTd.data("haveTable",true);
$firstTd.append('<table class="newTable"><tr><td>NEW TABLE</td></tr></table>');
} else {
$firstTd.data("haveTable",false);
$firstTd.children("table").remove();
}
});
https://jsfiddle.net/e3nk137y/1663/
try
$('#myTable').bootstrapTable().on('click-row.bs.table td', function (e, row, $element)
{
//....my operation
}
Based on my guess, when you click on that cell, you probably want only the triggers for that particular cell to execute and not for the whole table.
This can be achieved by stopping the propagation of event from the table cell to the table row.
$('#myTable').bootstrapTable().on('click-row.bs.table', function (e, row, $element){
//stop the propagation for target cell
if($(event.target).hasClass('myClass')) e.stopPropagation();
//the code for handler
...
...
}
There are many ways stopPropagation can be utilized to do this thing. This was just one of those.
Since I dont know how your other triggers are set, I can't write code that works with those with assumptions.
Try this:
$('#myTable tr td:last-child').on('click', function() {
if( $('.newTable', $(this)).length ) {
$('.newTable', $(this)).remove();
} else {
$(this).append( '<table class="newTable"><tr><td>NEW TABLE</td></tr></table>' );
}
});

Insert Table Row and Remove button from original row

I've got a form with a table with originally 1 row of input fields. Users can click the "New Row" button to get another row, with empty input fields. This leaves with me multiple copies of the "New Row" button for every Row - I would like to remove all but the most recently created "New Row" button (i.e. the one in the last row of input fields).
I've setup a sample JSFiddle at:
http://jsfiddle.net/fmdataweb/vRe9v/2/
Is there something I can add to the existing js that will delete the button that was clicked whilst leaving the newly created button in the new row? Here's the Javascript:
var table = $( '#nextYear' )[0];
$( table ).delegate( '#button2', 'click', function () {
var thisRow = $( this ).closest( 'tr' )[0];
$( thisRow ).clone().insertAfter( thisRow ).find( 'input:text' ).val( '' );
});
​
Use $(this).remove(); jQuery $(this) in the event of control represents the control whom event is fired on. You can use remove() method that will remove the button being click from dom
Live Demo
var table = $('#nextYear')[0];
$(table).delegate('#button2', 'click', function() {
var thisRow = $(this).closest('tr')[0];
$(thisRow).clone().insertAfter(thisRow).find('input:text').val('');
$(this).remove();
});​
You can use jQuery remove() which removes the set of matched elements from the DOM.
In your case as you are within the button click event, this is what references the button object in the DOM.
Turn this into a jQuery object and call remove() on it like this:
$(this).remove();
Complete new code:
var table = $('#nextYear')[0];
$(table).delegate('#button2', 'click', function() {
var thisRow = $(this).closest('tr')[0];
$(thisRow).clone().insertAfter(thisRow).find('input:text').val('');
$(this).remove(); // remove button that was clicked
});​
See DEMO
Try this: DEMO: http://jsfiddle.net/xRQs8/2/
It can be done using single button :+
<table id="dataTable" cellspacing="0" cellpadding="0" border="0" width="100%">
<tr>
<td>
<input type="Button" value="Add More" name="AddMore" class="AddOption" />
</td>
</tr>
</table>

Javascript modify parameters of an element's event function

I'm wondering if there is a more elegant means of modifying the parameter of an onclick event. I have a table that I am dynamically adding/removing elements from and I re-index the rows. Each row has a delete link that has the row's index (and a duplicate link) that needs to update its parameter to match the modified row id.
Currently my code looks like (simplified)
<a onclick="delRow(1)">delete</a>
and the javascript:
...
html = element.innerHTML;
html = html.replace(/dupRow(\\d+)/g, "dupRow(" + newIndex + ")");
html = html.replace(/delRow(\\d+)/g, "delRow(" + newIndex + ")");
element.innerHTML = html
and I would like it to become something along the lines of
if (element.onclick != null) {
element.onclick.params[0] = newIndex;
}
Any such way of accomplishing this? I also have jQuery if this helps.
Updates:
So thanks to the glorious help of #rich.okelly I have solved my issue
<script>
...
var newRow = '\
<tr>\
<td class="index" col="0">0</td>\
<td>this is content...</td>\
<td>Del</td>\
</tr>';
// re-index table indices in a non-efficient manner
function reIndexTable() {
$("#rpc-builder-table").find('.index').each(function (i) {
$(this).html(i)
})
}
// add row
function addRow() {
for (i = 0; i < $('#addRowCount').attr("value"); i++) {
$("#rpc-builder-table").append(newRow);
}
reIndexTable();
}
$(document).ready(function () {
// add row button
$('#addRowsButton').on('click', function () {
addRow();
});
// delete row
$('#rpc-builder-table').on('click', 'td a[row-delete="true"]', function () {
$(this).closest('tr').remove();
reIndexTable();
});
...
}
</script>
...
<div>
<label>Rows to add: </label>
<input id="addRowCount" value="1" size="2" />
<button id="addRowsButton">Add Row(s)</button>
</div>
<div><table id="rpc-builder-table"><tbody>
<tr>
<th>Idx </th>
<th>Some content (1)</td>
</tr>
</tbody></table></div>
...
I used the .on() function instead of the suggested .delegate() function since it is deprecated. Solution works well - hope it helps someone :)
If you change your html to something similar to:
<tr>
<td>
delete
</td>
</tr>
Then your javascript can be something like:
$('td a[data-delete="true"]').on('click', function() {
$(this).closest('tr').remove();
});
Update
If rows are added dynamically to a pre-exising table (table is interchangeable for any parent element), you can use the delegate method like so:
$('table').delegate('td a[data-delete="true"]', 'click', function() {
$(this).closest('tr').remove();
});
Instead of inline handlers, use event delegation to attach event handlers
$("#tableID").delegate("a", "click", delRow);
$("#tableID").on("click", "a", delRow); //jQuery 1.7
Inside the handler,
var row = $(this).closest("tr").index(); //Get the index of the parent row
Inline handlers get parsed into a function:
function onclick() {
delRow(1);
}
so changing them is difficult. Your example rewrites the entire row with the new parameter, which is bad practice.
The most brain dead solution is getting rid of the parameters and setting a variable isntead.
var row_to_dup = 42;
$("#a_row_dupper").bind('click', function (){
dupItem(row_to_dup);
});
//changing the row to dup
row_to_dup = 17;

Categories