I have the following function:
$("#example tbody").click(function(event) {
$(oTable.fnSettings().aoData).each(function (){
$(this.nTr).removeClass('row_selected');
});
$(event.target.parentNode).addClass('row_selected');
});
When a user clicks on a td element in a table it adds the row_selected class to the row. However when a user clicks on an input element inside of a td then it adds the row_selected
class to the td.
Is there a way that I can change event.target.parentNode so that instead of the parent
it adds the class to the parent tr?
Use closest().
$(event.target).closest('tr').addClass('row_selected');
Change your handler to use jQuery's event delegation instead of your own...
$("#example tbody").on("click", "tr", function(event) {
...then you can just use this...
$(this).addClass('row_selected');
You can use parentsUntil() function, that is sort of like finding ancestors. I cant remember the function for ancestors, but this will work:
$(event.target).parentsUntil("tr").addClass('row_selected');
you can try this
$(event.target).closest('tr').addClass('row_selected');
Instead of your line
$(event.target.parentNode).addClass('row_selected');
Using closest(), you will be able to apply row_selected class to nearest tr element of the element you click, that may be a td or any other element inside it.
Related
Say I have:
<a href="http://foo.com" class="SiteClass">
Then I via jQuery I do some tests and conditionally update the class depending on the outcome, for example adding SiteDown css via jQuery addClass method, resulting in:
<a href="http://foo.com" class="SiteClass SiteDown">
I have the following JavaScript which does not fire:
$("a .SiteDown").on('click', function(e){
e.preventDefault();
e.stopPropagation();
alert('Clicked SiteDown');
});
What do I need to be able to fire an alert (or any other code there) when a link with class SiteDown is clicked, keeping in mind this class can be added dynamically.
You selector is incorrect, remove space to convert it to element with class selector.
$("a.SiteDown").on('click', function(e){
//....
});
As of now its descendant selector.
As you are approach when manipulation selector, use Event Delegation using on().
$(document).on('click', "a.SiteDown", function(e){
//....
});
In place of document you should use closest static container.
In your code $("a .SiteDown") you are looking for an element that is child of a remove space and it will be ok. use $("a.SiteDown") meaning a with class SiteDown
I have this code:
$(".div").click(function ()
{
alert("hi");
});
...but when I create new div:
$("body").append("<div>1</div>");
...and click on this div, it doesn't say "hi".
I know that I can do onclick="callfunction()" on the div element, but I would like to avoid using that method.
Problems
You were attempting to create a bind on an element that didn't yet exist - so it couldn't be bound.
You used .div as a selector. The selector .div is looking for an element with class="div" rather than an element of type div.
Solution 1 - Delegation
With delegation you create a bind on an element that exists in the structure above where you will be dynamically adding an element that you want to listen for.
To use delegation, change to this:
$("body").on("click", "div", function ()
{
alert("hi");
});
Here is an example showing delegation vs binding on a future element without delegation:
Fiddle
Solution 2 - Bind to element on creation
The alternative would be to add the bind on the creation of the new element, that would look something like this:
$newEle = $("<div>1</div>").click( function() {
alert("hi");
});
$("body").append($newEle);
Fiddle
Use the appendChild() method to add the DIV to the end of your document. See: http://www.w3schools.com/jsref/met_node_appendchild.asp
Your other logic can follow the creation of the div.
Inside a number of <tr>'s in my document there are 7 classes, each one sometimes has a corresponding class name (i.e. sub, id, assigned, sub, sub, status, and one classless "td"). Within the td class = "status" lies a span class defined as either
<span class = "statusBox">Passed</span>
or
<span class = "statusBox">Failed</span>.
If the text contained within the span class is "Passed", I need to delete the entire <tr>. If it's failed it stays on the document. How can I achieve this?
My first attempt was through a call such as:
function() {
if ($('tr td span.statusBox').html() == "Passed"){
$('tr td span.statusBox').hide();
}
But this removed every instance of only the phrase "Passed", not the entire <tr>.
I've also tried
$("tr td span.statusBox:contains('Passed')").each(function(){
$(this).css("visibility","hidden");
});
I feel like this is more along the right path, but I can't seem to get it to work.
You were close: find the status box with the word 'Passed' and then find the closest ancestor tr element and remove it from the DOM:
$("tr td span.statusBox").filter(":contains('Passed')").each(function(){
$(this).closest('tr').remove();
});
Since the :contains operator is a jQuery extension (it has been deprecated from the CSS spec), it's faster to break the selector into two parts. The first is finding all spans of class statusBox, this will look up the elements using native browser methods. Then those elements are filtered using the :contains operator (which may have a native implementation or may be implemented in jQuery, depending on the browser).
It is because you are altering the visibility of the span instead of the parent <tr>. You can use $(this).closest('tr') to get to the row element and then alter its visibility.
$("tr td span.statusBox:contains('Passed')").each(function(){
$(this).closest('tr').css("visibility","hidden");
});
$(".statusBox").each(function (i, e) {
if ($(e).text() == "Passed") {
$(e).closest('tr').hide();
}
});
http://jsfiddle.net/B7Wqy/
I am aware that e.target contains the info of the element just below the cursor, but what if I want to know the class name of the div which has a table>tr>td>button in it and I'm clicking that button inside that td. I know this events bubbles up and there should be a way to find out if the div exists in that bubbling levels. Any help.
Scenario: button is inside a modal window. How do I find the modal windows class name on click of the button inside it.
Use .closest() to traverse up the DOM to the nearest match:
var parentDiv = $(yourButton).closest('div');
Or in the button's click:
$(yourButton).click(function() {
var nearestParentDiv = $(this).closest('div');
// And read its class
console.log(nearestParentDiv.attr('class'));
});
The selector .closest() accepts can of course be more specific than this, so if if the modal window <div> has some known class but you need to inspect its other classes, you should use the more specific selector.
Yes as you say the event will bubble up to your div, so just make the div handle the event with .on() , like this:
$('#yourdiv').on('click',':button',function(e) {
alert( $(e.delegateTarget).attr('class') );//alerts the classes of #yourdiv
alert( $(this).attr('id'));//alerts the id of the clicked button (if have one)
});
UPDATE:
Fixed obtaining the reference to the original div where the event was attached. With event.delegateTarget from the Event object . Thanks Cristophe and Kevin B. for spotting the error.
See working demo
You can use .parent() to get the parent div attributes like id: http://jsbin.com/ololad/1/edit
$('button').click(function(){
console.log($(this).parent().attr('id'));
});
I was thinking if there's a better solution for adding onclick handler to each cell in a table than this approach: Adding an onclick event to a table row
Better in the way that I wouldn't need to set "cell.onclick = function" for each cell.
I just need to get the coordinations of a cell where user clicked.
Thanks!
EDIT: The "coordinations" mean 0x0 for top-left cell, 0x1 for second cell in the first row etc.
Are you looking for this?
$(function(){
$("#tableId tr td").click(function(event) {
alert(event.pageX);
alert(event.pageY);
});
});
In case your table cells are generated dynamically:
$(function(){
$("#tableId tr td").live('click', function(event) {
alert(event.pageX);
alert(event.pageY);
});
});
.
Update Based On OP Comment:
To get top and left values you could try this:
$(function(){
$("#tableId tr td").click(function(event) {
alert($(this).offset().top);
alert($(this).offset().left);
});
});
As your other comment shows, you are probably looking to get the IDs of the clicked cell, you may try this:
$(function(){
$("#tableId tr td").click(function(event) {
alert($(this).attr('id'));
});
});
But for the above to work, it is assumed that all cells already have an id attribute.
You're looking for event delegation.
http://icant.co.uk/sandbox/eventdelegation/
among other examples. Basically observe some higher container such as the table for click events and then determine if you care to handle it by inspecting the event passed to the event handler.
So if the click happens inside the table, you can determine the target of the event and assuming there's a valid td present handle the event.
This has the benefit of allowing you to dynamically add more table cells without needing to add handlers to all of them.
jQuery in particular as an excellent delegate method for using this approach.
http://api.jquery.com/delegate/