Disconnecting click event of parent node using jQuery - javascript

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',"")
}

Related

Keypress action query using jQuery class attribute

I am implementing the view behavior using jQuery. I can input directly to the table td. I want to give an event when inputting to this td.
But the event is not recognized, what should I do?
Here is the code:
<div class="a">
<table class="tb">
<tr>
<td></td>
</tr>
</table>
</div>
<script type="text/javascript">
$(".a table tr td").on('keypress', function(event){
console.log(event);
});
</script>
It is an event required only on the page, so it is difficult to modify the common jQuery code that draws and enters the table.
Based on this:
A keypress event handler can be attached to any element, but the event
is only sent to the element that has the focus
So you need to have focusable element, see this to know what are the focusable element: Which HTML elements can receive focus?
If I have textbox in td everything going to be fine:
$(".a table tr td").on('keypress', function (event) {
console.log(event.key);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div class="a">
<table class="tb">
<tr>
<td><input /></td>
</tr>
</table>
</div>
The below code works, so if it doesn't work in your case, that probably means that the <input> field is not yet added by your other "common" code, at the time you add the keypress listener.
So the solution should be to first add the <input> fields, and after that you execute your key handler code.
<div class="a">
<table class="tb">
<tr>
<td><input type="text"></td>
</tr>
</table>
</div>
Execute this AFTER the input fields have been added
$(".a table tr td").on("keypress", function (event) {
console.log(event.key);
});
Working example here: https://jsfiddle.net/081cL2xu/

Activating td button using JavaScript

I have the following function, which is used to expand and collapse child tr rows from parent rows within a table, and also changes the text style of a tr to normal:
$( document ).ready(function() {
$('.parent').on('click', function(){
$(this).next('.child').toggle();
$(this).css('font-weight', 'normal');
<<< ADD COMMAND TO TOGGLE BUTTON HERE >>>
});
});
I also have the following hidden button within each tr, which I want to submit when a tr is clicked:
<button type="submit" name="read-button" formmethod="POST" value="{{ message.message_id }}" style="display: none;"></button>
Which command should I include alongside the JavaScript function, in order to achieve this? I believe it will be one of the following (provided by this answer), however I've only been using JS for a few days so I'm not sure how to include these in my code:
document.getElementById('read-button').submit();
changeAction('read-button','loginForm');
document.forms['read-button'].submit();
Sample html:
<form method=['POST']>
<table>
<tr class="parent">
<td>
<button type="submit" name="read-button" formmethod="POST" value="{{ message.message_id }}" style="display: none;"></button>
<a>Heres a cell</a>
</td>
<td>
<a>
Heres one more cell
<a>
</td>
</tr>
<tr class="child">
<td>
<a>
Some hidden info
</a>
</td>
<td>
<a>
More hidden info
</a>
</td>
</tr>
<table>
</form>
To answer the specific question of how to trigger a button within a td via clicking on the tr:
$('.parent').on('click', function() {
$(this).find("button").click();
that can be improved by giving the button a class (incase you add additional buttons in future), eg:
<button class='readbutton' ..`
then
$('.parent').on('click', function() {
$(this).find("button.readbutton").click();
In this scenario, it seems that you don't need a hidden button as you can call the functionality of the hidden button directly.
So rather than:
$("button").click(handleClick);
use
$('.parent').on('click', function() {
.. other functionality ...
handleClick();
as you're new to js, note the difference between handleClick and handleClick() - with () it calls the function, without it passes it as a function variable.
$("button").click(handleClick);
is the same as
$("button").click(function() { handleClick(); });
If you're trying to submit a form, then you would use $(form).submit() - but there's no form in the code as pointed out in the comments and an ajax call would seem more appropriate here than submitting a form.
Finally, consider using classes rather than setting the css directly as adding/removing classes it quite simple in jquery eg for your tr click event add:
$(this).addClass("selected").siblings().removeClass("selected");

Mark row for deleting using checkbox

I have this inbox or mails which I needed to mark using checkbox for multiple deletions. The problem is that when I click the checkbox it always go to method read() because of onclick inside the tag. All I want is simple marking. Please see the code below:
#foreach ($messages as $message)
<tr onclick="document.location='{{route('account.message.read', array($message->id))}}'">
<td> <input type="checkbox" name="msg" value="{{$message->id}}"></td>
<td><strong>{{Str::words($message->subject, 5, '...')}}</strong> {{Str::words($message->message, 20, '...')}}</td>
</tr>
#endforeach
Now how can I mark each row without going inside that method? I am a newbie btw.
All you need to is attach handler to checkbox and use stopPropagation from bubbling up into trees, see below example :
HTML
Supposed we have table rows with onclick inline javascript and inside it have input:
<table>
<tr onclick="return alert('Hai')">
<td>
<input type="checkbox" />Click Me
</td>
</tr>
<table>
And here the handler :
$('input').click(function(e){
// normally if we removed this line of code
// alert will getting called as checkbox is checked/unchecked
// was inside table rows
// but with this propagation, we disabled it
// from bubbling up into tree
e.stopPropagation();
});
DEMO
you could put the onclick inside the tags excluding the checkbox cell
otherwise you could call an actual onclick function while capturing the click event and check that x is greater than lets say 50px!
<script type="text/javascript">
document.getElementById('emailRow1').addEventListener("click",function(e){
var x=e.pageX-this.offsetLeft;
if(x>50){
rowClicked();
}
},true);
</script>
<table><tbody><tr id='emailRow1'><td style="width:50px;">This area wont trigger onclick</td><td>I trigger onclick</td><td>i trigger onclick</td>
Then you can set custom parameters on your object and recall them using this.customPropertyName to determine what row was clicked! hope this helps

show/hide not functioning

<table class='generic'>
<script>
$('#select_bh').click(
function(){
if($('#select_bh')[0].checked){
$('#hide_box_bh_s').show();
}
else{
$('#hide_box_bh_s').hide();
}
}
);
</script>
<tr>
<td>
<b><input type="checkbox" id="select_bh" name="pj_boilerhouse" value="Boiler_House"/>Boiler House</b>
</td>
</tr>
<tr>
<td>
<span id='hide_box_bh_s' style='display:none'>
<b><input type="checkbox" class="case_bh_s" name="pj_bh_s" value="Structural"/> Structural</b>
</span>
</td>
</tr>
</table>
the show show/hide in JavaScript is not functioning.. some advice pls, thx.. some how it goes like this when i check the checkbox it will have a new row under the existing row
its working here you can see the code http://jsfiddle.net/damian_silvera/9ym5Y/
You should put your codes inside document ready handler, your code doesn't work as you have bound the event handler to an element that is not added to the DOM yet. The codes that are within the ready handler are executed after the DOM is fully loaded. Also note that Java is not JavaScript.
$(document).ready(function(){
$('#select_bh').click(function(){
$('#hide_box_bh_s').css('display', this.checked ? 'block' : 'none');
});
})
I have used conditional operator which is a shortcut for if statement, if the checkbox is checked it sets the value of display property to block otherwise it sets it to none.
ready()
css()
conditional operator

Delete a table row with javascript / jquery

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>

Categories

Resources