Delete row from table using JQuery. Please see code - javascript

I used a code which I got in the net that adds a table row every onclick event. It worked perfect for me until I realized I needed to have an onclick event for every row that when clicked, it will delete the row.
Is there a way for that to happen using my code?
Please see codes below:
Javascript/JQuery code:
<script>
var counter = 2;
function addRow() {
event.preventDefault();
var newRow = jQuery('<tr><td><label>'+ counter +'</label></td><td><textarea name="txtActionStep' + counter + '" style="width:300px; height: 50px; word-wrap:break-word;"></textarea></td><td valign="top"><input type="text" name="txtOwner' + counter + '"/></td></tr>');
counter++;
jQuery('table.actionsteps-list').append( newRow );
}
</script>
HTML Code:
<table class="actionsteps-list" width="510">
<tr>
<th colspan="3" align="left">Action Steps</th>
</tr>
<tr>
<td>Step #</td><td>Action Step</td><td>Owner</td>
</tr>
<tr>
<td><label>1</label></td>
<td><textarea name="txtActionStep1" style="width:300px; height: 50px; word-wrap:break-word;"></textarea></td>
<td valign="top"><input type="text" name="txtOwner1" /></td>
</tr>
</table>
<table width="510">
<tr>
<td align="right">Add Action</td>
</tr>
</table>
Thank you!

Sure, using delegation we can accomplish that.
$('table.actionsteps-list').on('click', 'tr', function(e){
$(this).remove();
});
You probably want to add a button to your row to signal a deletion, so let's assume you add (to each row):
<td><button class="delete">Delete</button></td>
Then just change your delegation method like this:
$('table.actionsteps-list').on('click', '.delete', function(e){
e.preventDefault(); // stops the page jumping to the top
$(this).closest('tr').remove();
});

Use a delegate ot catch the event at the table level, that way any new row that you add will also be handled:
$('.actionsteps-list').on('click', 'tr', function(){
$(this).remove();
});
Side note:
Don't use the javascript: protocol for inline Javascript, that's only used when you put Javascript in the href attribute of a link:
Add Action

Related

How do I pass (or reference) "$(this)" from html event?

Let's say I have a button in a table which adds a new row to a table:
<td><a onclick="addRow()"></a></td></tr>...
and I want to reference $(this) or $(this).closest('tr') from the function at the bottom of the page.
function addRow(){
$(this) // contains all information from the row which pressed the button
}
Simply passing a javascript variable from the HTML will result in null (as expected). Is there a way to reference the row that pressed the button?
The RECOMMENDED way of doing this is unobtrusive and delegated - give the link a class:
var $tb = $("#someTable");
$tb.on("click", ".addRow", function(e) { // delegation to allow new rows' links to work
e.preventDefault(); // stop any click side effects
var $row = $(this).closest("tr");
$tb.append($row.clone())
});
a { text-decoration:none }
td,th { padding:3px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>Add</th>
</tr>
</thead>
<tbody id="someTable">
<tr>
<td>1st</td>
<td>2nd</td>
<td><a class="addRow" href="#">+</a></td>
</tr>
<tr>
<td>3rd</td>
<td>4th</td>
<td><a class="addRow" href="#">+</a></td>
</tr>
</tbody>
</table>
Use this
<td><a onclick="addRow(this)"></a></td></tr>
and then:
function addRow(e){
console.log($(e)) // contains all information from the row which pressed the button
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a onclick="addRow(this)">Clickme</a>
You can reference the row that you clicked using an event.
<td>Add</td>
and in javascript you can check the event
<script>
function addRow(event) {
console.log(event);
}
</script>

when i append something using the append function i dont have control over it using jquery

this is a simple demonstration of what i have, this is a table with a single row in it,
<table id="test_table">
<tr>
<td>name</td>
<td>age</td>
<td>action</td>
</tr>
<tr>
<td>test name</td>
<td>20</td>
<td class="delete">delete</td>
</tr>
</table>
and if i click on the delete td this row would be hidden
$('.delete').click(function(){
$(this).parent().parent().hide();
});
and i have a simple form of name and age, when i click on the add button it appends it to the table
$('#test_input').click(function(){
var name = $('#name').val();
var age = $('#age').val();
$('#text_table').append('<tr><td>'+name+'</td><td>'+age+'</td><td class="delete">delete</td></tr>');
});
the problem is i if i click on the new appended row it would hide like its not even there, what ever i try to do using the appended row, it wouldn't take it, is there something wrong that im doing ?
$('#test_table') should be $('#test-table').
And you should bind the on-click on the added row.
Another solution is to create a delegated event.
$('body').on('click', '.delete', function() {
$(this).parent().parent().hide();
});

How to handle a TR click without the first and last TD

I have a Datatables Table with some random values in it. I would like to create a popup when the client clicks on the TR itself, but NOT on the first and the last TD of the table.
<table class="table href="#popup">
<tr id="tr1">
<td><input type="checkbox"></td>
<td>Test1</td>
<td>Test1</td>
<td><input type="checkbox"></td>
</tr>
<tr id="tr2">
<td><input type="checkbox"></td>
<td>Test1</td>
<td>Test1</td>
<td><input type="checkbox"></td>
</tr>
<tr id="tr3">
<td><input type="checkbox"></td>
<td>Test1</td>
<td>Test1</td>
<td><input type="checkbox"></td>
</tr>
<tr id="tr4">
<td><input type="checkbox"></td>
<td>Test1</td>
<td>Test1</td>
<td><input type="checkbox"></td>
</tr>
</table>
My popup plugin works like, if an href link is called and the popup div's id equals to that href value, it automatically pops up.
However if someone clicks on the first or the last TD do NOT want the popup to activate. Is it actually possible to achieve this somehow?
(The following solution should not be mentioned, because it would make the code look like a mess literally: if I select all the TD fields without the first and last, and add a href attribute to all of the selected TD elements.)
Any other suggestions are welcomed!
When you click, the event is propagated from the child nodes to the parent nodes (learn more here).
You can disable event propagation in both td:first-child and td:last-child elements inside your table in order to prevent your tr event handler from being reached.
I'd also suggest you to use event delegation to keep better performance.
$('.table').on('click', 'tr', function() {
alert('show popup');
});
$('.table').on('click', 'td:first-child, td:last-child', function(e) {
e.stopPropagation();
});
FIDDLE: http://jsfiddle.net/6QTrL/1/
Just use this:
Using :first-child and :last-child with not()
$('table tbody tr td').not(":first-child").not(":last-child").click(function(
//This will only be triggered on the td that are not the first or the last on a tr
))
Here's a fiddle to accomplish that - First and Last row now clickable
I have the first and last row throwing an alert but that's just to give you an idea of how to target them.
$(function(){
var tableRows = $('table').find('tr');
$('table').on('click', 'tr', function(){
if (this == tableRows[0])
alert('first row');
else if (this == tableRows[tableRows.length - 1])
alert('last row');
else
alert('somewhere in the middle');
});
});
The code below is probably more along the lines of what you're looking for. I made the code above in the fiddle so I just pasted that as well.
$(function(){
var tableRows = $('table').find('tr');
$('table').on('click', 'tr', function(){
if (this != tableRows[0] && this == tableRows[tableRows.length - 1])
alert('somewhere in the middle');
});
});

delete table row

I have a table like this:
<table>
<tr>
<td>foo</td>
<td><button>delete</delete></td>
</tr>
<tr>
<td>foo</td>
<td><button>delete</delete></td>
</tr>
</table>
I want to use JQuery to install a click handler on the delete buttons such that it deletes the current row when clicked
Give a class of, for example, "delete" to the delete buttons, then use this:
$("button.delete").click(function() {
$(this).closest("tr").remove();
});
Alternatively, if you can't add the class, you can use the :contains selector:
$("button:contains('delete')").click(function() {
$(this).closest("tr").remove();
});
Update (now that the code in the question has completely changed)
Now that you have changed the code in the question to contain only one button instead of two, you don't need to bother adding the class, or using the :contains selector, you can just use the plain old button selector:
$("button").click(function() {
$(this).closest("tr").remove();
});
Try this. As a side not you should not have same id to any dom element on the page.
$("button").click(function() {
$(this).closest("tr").remove();
});
In your markup the tags are not closed properly. E.g the button tag is not closed properly so the selector will not work. Give a unique id or a class name to select the required buttons.
Something like this
<tr>
<td>foo</td>
<td>Some content</td>
<td><input type="button" class="delete" value="Delete" /></td>
</tr>
Using delegate to attach event handler only to table for better performance. This way the click event will be attached only to the table element no matter how many rows it has.
$("table").delegate("input.delete", "click", function() {
$(this).closest("tr").remove();
});
You can try soemthing like this:
<table>
<tr>
<td>row 1, cell 1</td>
<td><img class="delete" src="del.gif" /></td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td><img class="delete" src="del.gif" /></td>
</tr>
</table>
And your jQuery:
$('table td img.delete').click(function(){
$(this).parent().parent().remove();
});
First off, there's a syntax error in your HTML, and you should a class identifier for easier access to those buttons:
<table>
<tr>
<td>foo</td>
<td><button class="delete">delete</button></td>
</tr>
<tr>
<td>foo</td>
<td><button class="delete">delete</button></td>
</tr>
</table>
Next, here's the jQuery code you need:
$(function() {
$('button.delete').click(function(event) {
event.preventDefault();
$(this).closest('tr').remove();
});
});

How to add hyperlink to table row <tr>

I am having a table with its table row <tr> generating in a loop to form multiple rows.
I want to give separate <a> link to each <tr>. Since in table we can add only add data to <td> only, I am not able to achieve that.
Is there any other way to achieve this?
Html:
<table>
<tr href="http://myspace.com">
<td>MySpace</td>
</tr>
<tr href="http://apple.com">
<td>Apple</td>
</tr>
<tr href="http://google.com">
<td>Google</td>
</tr>
</table>
JavaScript using jQuery Library:
$(document).ready(function(){
$('table tr').click(function(){
window.location = $(this).attr('href');
return false;
});
});
You can try this here: http://jsbin.com/ikada3
CSS (optional):
table tr {
cursor: pointer;
}
OR the HTML valid version with data-href instead of href:
<table>
<tr data-href="http://myspace.com">
<td>MySpace</td>
</tr>
<tr data-href="http://apple.com">
<td>Apple</td>
</tr>
<tr data-href="http://google.com">
<td>Google</td>
</tr>
</table>
JS:
$(document).ready(function(){
$('table tr').click(function(){
window.location = $(this).data('href');
return false;
});
});
CSS:
table tr[data-href] {
cursor: pointer;
}
Playing off of #ahmet2016 and keeping it W3C standard.
HTML:
<tr data-href='LINK GOES HERE'>
<td>HappyDays.com</td>
</tr>
CSS:
*[data-href] {
cursor: pointer;
}
jQuery:
$(function(){
$('*[data-href]').click(function(){
window.location = $(this).data('href');
return false;
});
});
The easiest way I've found to turn a table row into a link is to use the onclick attribute with window.location.
<table>
<tr onclick="window.location='/just/a/link.html'">
<td></td>
</tr>
</table>
I agree with the first response, more information is needed. But if you're just trying to make a table of links, you can just do
<tr><td>...</td></tr>
If you're saying that you want to make each <tr> clickable, you can add a click event to each <tr>, or better yet, add a .delegate() handler to the table that manages clicks on its <tr> elements.
$('#myTable').delegate('tr','click',function() {
alert( 'i was clicked' );
});
This code assumes your table has the myTable ID:
<table id="myTable">
<tr><td> cell </td></tr>
<tr><td> cell </td></tr>
</table>
If this isn't what you meant, then please clarify your question, and post the relevant javascript code you're using.
PHP:
echo "<tr onclick=\"window.location='".$links[$i]."'\">......";
Javascript without jQuery:
x=1;
.
.
for (...) {
var tr=document.createElement('tr');
tr.onclick=function() { window.location='page'+(x++)+'.html'}
tr.style.cursor='pointer';
.
}
will let the user click on each row
you can use an array to load the pages too:
x=0;
var pages=["pagea.html","pageb.html"]
.
.
for (...) {
var tr=document.createElement('tr');
tr.onclick=function() { window.location=page[x++];}
tr.style.cursor='pointer';
.
}
The premium suggestion would be to add the tags when you generate the table. If you need to do it after the table is rendered and you want to use javascript you can always add something like
var mytable = document.getElementById("theTable")
var myrows = mytable.rows
for(i=0;i < myrows.length;i++)
{
var oldinner;
oldinner = myrows[i].cells[0].innerHTML;
myrows[i].cells[0].innerHTML = "<a>" + oldinner + "</a>";
}
or if you need to do it to every cell, your can always
var mytable = document.getElementById("theTable")
var myrows = mytable.rows
for(i=0;i < myrows.length;i++)
{
mycells = myrows[i].cells;
for(a=0;a < mycells.length;a++)
{
var oldinner;
oldinner = mycells[a].innerHTML;
mycells[a].innerHTML = "<a>" + oldinner + "</a>";
}
}
I hope you find this helpful
<tr><td><a></a></td></tr>
this?
jQuery.wrap the returned anchor to a td and then add to tr and jQuery.appendTo table
$('ith anchor element in array').wrap('<td />').wrap('<tr />').appendTo('table#table_id');
You can simply gen the with and inside as Nicole suggested:
<tr><td>title of the url</td></tr>
Or put the url in the tr tag like
With jQuery included
$('tr.clickable').click(function(){
window.location = $(this).attr("title");
});
to bring you to that page on click (basically hacking a tr to work like a tag (just a thought, never really try it.
add in
and change display style to display:block
and add same size for like this:
CSS:
#Table a {
display:block;
}
#Table td {
width:100px;
hright:100px
}
HTML:
<table id="Table">
<tr><td><a onclick="" href="#"> cell </a></td></tr>
<tr><td> cell </td></tr>
</table>
You can use data-href script to add href in any html elements. It makes html valid since it add only data-href attribute to a element.
https://github.com/nathanford/data-href/

Categories