Delete a table row with javascript / jquery - javascript

This is not working. Firebug is not throwing any error though.
HTML:
<table>
<tr><td>BookA</td><td>Delete</td></tr>
<tr><td>BookB</td><td>Delete</td></tr>
<tr><td>BookC</td><td>Delete</td></tr>
<tr><td>BookD</td><td>Delete</td></tr>
</table>
Javascript:
function deleteRow(ref) {
$(ref).parent().parent().remove();
}
If possible, I would like to use a solution with inline javascript

First of all, inline JavaScript (href="javascript:x" or onclick="x") is generally bad. With inline JavaScript, you won't have access to the event object, and you can't really be sure what this references to.
jQuery (and almost every other JavaScript library/framework) has built-in event handling. So, your code would look like this with event handlers:
$('a.red').click(function(e) {
e.preventDefault(); // don't follow the link
$(this).closest('tr').remove(); // credits goes to MrKurt for use of closest()
});
And here's a demo: http://jsbin.com/okaxu

Try this:
// Bind all the td element a click event
$('table td.deleteRow').click(function(){
$(this).parent().remove();
});
By the way, it'll remove the javascript from your html code.
With this html code
<table>
<tr>
<td>BookA</td>
<td class="red deleteRow">Delete</td>
</tr>
<tr>
<td>BookB</td>
<td class="red deleteRow">Delete</td>
</tr>
<tr>
<td>BookC</td>
<td class="red deleteRow">Delete</td>
</tr>
<tr>
<td>BookD</td>
<td class="red deleteRow">Delete</td>
</tr>
</table>

remove inline scripting
<script>
$(function(){
$('table td a').live('click', function(){
$(this).parents('tr').remove();
return false;
});
});
</script>

This won't work because $(this) isn't referring to the a-tag as you think (I think its referring to the window object or something)
Instead of using inline javascript in the href-attribute do this
Instead do this
<script type="text/javascript">
$("table a").click( function() {
$(this).parent().parent().remove();
});
</script>

I believe you have a bug in your deleteRow function. Here's how it should be written:
function deleteRow(ref) {
ref.parent().parent().remove();
}
The ref that you are passing into deleteRow is already a jQuery object. You shouldn't use $(ref), just ref alone since ref is already a jQuery object.

I would have to agree that inline javascript should be avoided, but if there is some other reason that it is necessary or beneficial to use it, here's how.
<table>
<tr><td>BookA</td><td>Delete</td></tr>
<tr><td>BookB</td><td>Delete</td></tr>
<tr><td>BookC</td><td>Delete</td></tr>
<tr><td>BookD</td><td>Delete</td></tr>
</table>

Related

Disconnecting click event of parent node using jQuery

I have a <td> which contains a <span> tag. The td tag has a click event and the <span> tag has an id. On clicking the span, I want to disconnect the click event of the <td> tag. How do I do by referring to the span tag?
<Table>
<tr>
<td onClick="disconnectHandler();"><span id="testin">Hello</span></td>
</tr>
</Table>
This is what my JavaScript has :
function disconnectHandler()
{
alert("Hi Hello");
$("#testin").parent().unbind();
}
It keeps showing the alert box. What is wrong with this code?
Additionally, i want to attach the click event to it later too after removing it!
The first unbind scenario doesn't work, because of jQuery's event model. jQuery stores every event handler function in an array that you can access via $("#foo").data('events'). The unbind function looks just for given function in this array. So, you can only unbind() event handlers that were added with bind()
Reference.
Working fiddle.
You couldn't use unbind but you could remove the onclick attribute using prop():
function disconnectHandler()
{
alert("Hi Hello");
$("#testin").parent().prop('onclick',null);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td onClick="disconnectHandler();"><span id="testin">Hello</span></td>
</tr>
</table>
If you want to disable the click after first click it will be better to use one(), check the example below.
Description : one() Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
Hope this helps.
$(function(){
$('body').one('click', '#testin', function(){
alert("Hi Hello");
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><span id="testin">Hello</span></td>
</tr>
</table>
This will bind a click event only once on the td element
$(document).ready(function() {
$('#testin').one('click', function(){
alert('Hello there');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><span id="testin">Hello</span>
</td>
</tr>
</table>
EDIT
The main difference between my answer and Zakaria's reside in the fact the he can add more span later on (if you use class instead of id that is).
$('body').one('click', '#testin', function(){}); Binds all #testin inside body to a click event.
$('#testin').one('click', function{}); Binds all #testin that are already on the document to a click event.
EDIT 2
to answer your question:
It keeps showing the alert box. What is wrong with this code?
You haven't binded an event to the td element, every time it is clicked it call a function name disconnectHandler().
function doSomething() {
alert('alerted')
}
function removeEvent() {
document.getElementById('doer').removeEventListener('click', doSomething);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="doer" onclick="doSomething()">Click me</p>
<p id="undoer" onclick="removeEvent()">Remove his event</p>
As you can see, the so-called event is part of his DOM. You are not removing the attribute, that is why it still call the function
this can also be tried
function disconnectHandler()
{
alert("Hi Hello");
$("#testin").parent().attr('onclick',"")
}

Trying to get the attribute of clicked object

I'm trying to get the headers value from the object when I click on its link.
For the example I'm trying to get the value "2014_BUDGET" when I click on the link.
I've tried all sorts of variations.
Tried getting .prop() instead of .attr.
Tried searching .closest('td')
Tried getting the parent attr.
All end with an alert with 'undefined'.
Here is my code
<td headers="2014_BUDGET" class="MYCLASS">1</td>
<td headers="2014_BUDGET" class="MYCLASS">1</td>
In href this points to the global window object.
Use onclick instead.
<td headers="2014_BUDGET" class="MYCLASS"><a href="#"
onclick="alert(this.parentNode.getAttribute('headers')); return false">1</a></td>
$(document).ready(function(){
$("a.anchor").on("click", function(e) {
e.preventDefault();
alert($(this).closest("td").attr("headers"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td headers="2014_BUDGET" class="MYCLASS">1</td>
<td headers="2015_BUDGET" class="MYCLASS">2</td>
</tr>
</table>
Try this;
<td headers="2014_BUDGET" class="MYCLASS">1</td>
It's essentially the same answer as Gurvinder372, however, that answer targets the A tag, rather than the TD tag.
1
Edit
Never mind, he has updated his answer. Ignore this one.

How to detect if this radiobutton is checked?

I read a lot of things on stackoverflow, but nothing help me :(
I have this HTML table, loaded by ajax request :
<table class="table table-striped table-hover choix_annonce_table">
<thead>
<tr>
<th>Sélection</th>
<th>Visuel</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="radio" value="45" name="idAnnonce"></td>
<td><img alt="Annonce 1" src=""></td>
</tr>
<tr>
<td><input type="radio" value="46" name="idAnnonce"></td>
<td><img alt="Annonce 2" src=""></td>
</tr>
</tbody>
</table>
I try to detect when radiobutton is checked, but no of the following issues work (in js file included on my "main" page):
$(document).ready(function() {
$("input[name=idAnnonce]").click(function(){
alert("xx");
});
});
OR
$(document).ready(function() {
$("input[name=idAnnonce]:radio").change(function () {
alert("xx");
});
});
Do you have in idea?
EDIT : when I load JS directly into my loaded table with ajax, it works.
Why ?
This happens because the .click() and .change() methods, along with all other event handlers, only watch for these events on elements that are present at the time the events are attached.
To solve this, instead of using this:
$('input[name=idAnnonce]').change(function() {
// ...
});
Use something like this instead:
/* Use 'body' or any element that will contain the form */
$('body').on('change', 'input[name=idAnnonce]', function() {
// ...
});
This will watch for click events passing up to the body, and only call the function for those that match the selector.
If your javascript is loaded directly into the html file, then it's being executed in line as the html file is loaded and parsed. When the javascript is in a separate file, it needs to be invoked. You could do this by executing an "onload" function as part of your body tag statement. That part of your html is missing, so it's unclear whether you're actually loading anything when your table is loaded. You can also execute these event monitors through a callback at the end of the ajax load.
When loading the table via ajax, you will need to bring in the javascript through the ajax call. Meaning the table that comes in should also contain the javascript that references the table. The DOM on the parent page doesn't know about the table, so the javascript on the parent page won't act on new content.
$(document).ready(function() {
$('input[type=radio][name=idAnnounce]').change(function(evt) {
console.log(evt.target.value)
});
});
The selector you were using was wrong.
The above code should help
cheers

How to pass parameters from dynamic table to the event handler without inline javascript hanlder

As I heard, I should avoid using inline javascript handler on html. e.g. onclick = "FUNCTION_NAME".
If I have a table that is generated dynamically, Each row has a button for its own.
If I don't use incline Javascript function, how can I pass some parameters from the table to the event handler?
Maybe passing the data from the table cell is not very hard. What if some data is not shown on the table cell (for security reason), for example, a secret ID number that is used internally within the application and is not supposed to exposure on the html (Setting it in the invisible cell in the table is not safe because people who knows html can still inspect it). How can we pass those data that is not shown on the table from dynamic table to event handler in this case?
If we use inline click attribute, i.e. onclick="javascript_function(parameter_1, parameter_2)" on each row, that's fairly easy to pass any data I want, and I do not need to show those kinds of secure data on the html in order to pass it.
If you use jQuery, I would recommand
<table class="with-val">
<td data-val="17">17 points</td>
</table>
and
$('.with-val').on('click', 'td', function() {
var val = $(this).data('val');
console.log(val) //17
});
This way (with the on(eventType, selector, handler) signature), you don't have to reset the events if rows are deleted or added,
and the markup is much lighter (and it is considred best practice, as you add only one event handler for the whole table).
Giving markup
<td class="val" data-val="17">17 points</td>
you can get value from binding like this:
$('.val').on('click', function() {
var val = $(this).data('val');
console.log(val) //17
});
For this:
Setting it in the invisible cell in the table is not safe because
people who knows html can still inspect it
You must not send secure data in any way to frontend. User can stop your code with breakpoints, debug or anything else, and get this data even when it is not visible in html. In addition this data will be visible in responses for the requests that browser send
You can use click event to call a function, that does the task of getting the value of any paramater you wish.
Hope this helps.
<td><button id="btn">Click me</button></td>
<td><input type="hidden" id="secret_id"></td>
$("#btn").click(function(){
var id = $("#secret_id").val();
alert(id);
});
This is a possible solution:
HTML:
<table border="1">
<thead>
<tr>
<th>HEAD1</th>
<th>HEAD2</th>
<th>HEAD3</th>
</tr>
</thead>
<tr>
<td class="hiddenField">row1 col1</td>
<td>row1 col2</td>
<td><button class="seeHidden">btn1</button></td>
</tr>
<tr>
<td class="hiddenField">row2 col1</td>
<td>row2 col2</td>
<td><button class="seeHidden">btn2</button></td>
</tr>
</table>
CSS:
th:nth-child(1), td:nth-child(1){
display: none;
}
jQuery:
$(".seeHidden").click(function(){
var hiddenField = $(this).parent()
.siblings("td.hiddenField")
.html();
alert(hiddenField);
});
Check this link jsfiddle to see a working example.
Hope it's useful!

How to add datas in a <tr> table in JQuery

I am trying to add some data in the following table structure :
<table>
<tr id = "line_one">
<!-- datas here -->
</tr>
<tr id = "line_two">
<!-- or data here -->
</tr>
</table>
I already tried in JQuery the following call to .appendTo() :
<script type = "text/javascript">
$(document).ready(function() {
$("#line_one").appendTo("<td>test</td>");
}
</script>
Does anyone has a clue of what happened wrong on this short code ?
Use .append() in your case and not .appendTo() .
.appendTo() will append tr to td
$("#line_one").append("<td>test</td>");
Also
$(document).ready(function(){
………
});
Closing paranthesis missing.
You want to use append, not appendTo.
As is it, you're appending #line_one to a newly created DOM object <td>test</td> and just keeping it in memory.
Try to use append instead of appendTo
<script type = "text/javascript">
$(document).ready(function() {
$("#line_one").html("<td>test</td>");
}
</script>

Categories

Resources