Click elsewhere not working in jquery - javascript

I got this code:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('td').click(function() {
if($('#edit').length == 0) {
var idz = $(this).parent().attr('id');
var textz = $(this).text();
var rowz = $(this).attr('id');
$(this).append('<textarea id=\"edit\" style=\"position:absolute;left:0;top:0;z-index:1;\">'+textz+'</textarea>').focus();
}
});
if($('#edit').length > 0) {
$('html:not(#edit)').click(function() {
$('#edit').remove();
});
}
});
</script>
<div class="table">
<table>
<tr>
<td>ID</td>
<td>Client</td>
<td>Category</td>
<td>Active</td>
</tr>
<tr id="2">
<td>2</td>
<td>Client 2</td>
<td>1</td>
<td>1</td>
</tr>
<tr id="1">
<td>1</td>
<td>Client 1</td>
<td>2</td>
<td>1</td>
</tr>
</table></div>
What I'm trying to do here is to intercept a click on any table cell and open a small textarea with the cell's value. IT WORKS OKAY.
But the peoblem is I'm trying to close the textarea by clicking elsewhere but not the #edit. So, this part of code doesn't work:
if($('#edit').length > 0) {
$('html:not(#edit)').click(function() {
$('#edit').remove();
});
}
I tried various ways of if/else statements, one if in another and so on and it still doesn't work. Please give me a hint of what's wrong with me.

The #edit element doesn't exist on first pageload, so the event handler is never bound as the condition fails.
Also, html:not(#edit) is usually not the way to go, attach the event handler to the document and check if the click originated from within #edit, if not remove #edit.
Change this
if($('#edit').length > 0) {
$('html:not(#edit)').click(function() {
$('#edit').remove();
});
}
to
$(document).on('mousedown', function(e) {
if ( ! $(e.target).closest('#edit').length )
$('#edit').remove();
});
FIDDLE

Related

bug removing an entire row in a table using addEventListener

I need to remove an entire row in a table by clicking into a cell with the tag (remove), it works, but if I click in any other cell, the row is removed too. here is the HTML and JS code below to demonstrate using event bubbling aproach:
var table1 = document.querySelector("#tableOne");
table1.addEventListener("click", function(event) {
event.preventDefault();
event.target.parentNode.parentNode.remove();
});
<html>
<head></head>
<body>
<table>
<thead>
<tr class="product">
<td></td>
<td>Name</td>
<td>Amount</td>
<td>Price</td>
<td>Total</td>
<td>(remove)</td>
</tr>
</thead>
<tbody id="tableOne">
<tr class="product">
<td><img src="imagens/tablet.jpg"></td>
<td>Tablet miPad 18</td>
<td>1</td>
<td>499.99</td>
<td class="item-total">499.99</td>
<td>(remove)</td>
</tr>
<tr class="product">
<td><img src="imagens/phone.png"></td>
<td>Telephone miPhone 18</td>
<td>2</td>
<td>199.99</td>
<td class="item-total">399.98</td>
<td>(remove)</td>
</tr>
<tr class="product">
<td><img src="imagens/shoe.jpg"></td>
<td>Shoe</td>
<td>1</td>
<td>99.99</td>
<td class="item-total">99.99</td>
<td>(remove)</td>
</tr>
</tbody>
</table>
</body>
</html>
the expected result is to remove the row only if I click on (remove)
If i could have some way to add a EventListener to every .removeItem would be great. Thanks everyone and Happy Easter!
You can filter events to only those where the target is a removeItem link:
var table1 = document.getElementById('tableOne');
table1.addEventListener('click', function (event) {
if (!event.target.classList.contains('removeItem')) {
return;
}
event.target.parentNode.parentNode.remove();
event.preventDefault();
});
but keep in mind that only works if the link is guaranteed to be the target when it’s clicked, i.e. when the link has no element children. Given that problem and jQuery (yeah, I know), this is more reliable:
$("#tableOne").on('click', ".removeItem", function (e) {
$(this).closest(".product").remove();
e.preventDefault();
});
If the table doesn’t have rows added dynamically, you can add event listeners to every one (questionable, but convenient):
var removeLinks = document.getElementsByClassName('removeItem');
for (var i = 0; i < removeLinks.length; i++) {
removeLinks[i].addEventListener('click', function (e) {
this.parentNode.parentNode.remove();
e.preventDefault();
});
}
and it’s possible to also bring the jQuery convenience over:
function closest(className, element) {
while (element && element.nodeType === 1) {
if (element.classList.contains(className)) {
return element;
}
}
return null;
}
var table1 = document.getElementById('tableOne');
table1.addEventListener('click', function (e) {
var link = closest('removeItem', e.target);
var row = closest('product', link);
if (!link) {
return;
}
row.remove();
e.preventDefault();
});

How to insert after 2nd element?

How can I insert something after the second form with mform class, for this markup:
<table id="sortme">
<tr>
<td>1</td>
<td><form class="mform"></form></td>
</tr>
<tr>
<td>2</td>
<td><form class="mform"></form><!---Insert Me here !---></td>
</tr>
<tr>
<td>3</td>
<td><form class="mform"></form></td>
</tr>
</table>
To insert after the first form, I can use:
$(function () {
$('<div>block</div>').insertAfter("#sortme form.mform:first");
});
so I've tried this code for the second, didn't work:
$(function () {
$('<div>block</div>').insertAfter("#sortme > form.mform:nth-child(2)");
});
Try .insertAfter("#sortme form.mform:eq(1)");
You, also, may use a counter, conditional statement and append as follows:
<script>
$(document).ready(function(){
counter = 0;
$(".mform").each(function(){
if (counter === 1){
$(this).append("<div>Block</div>");
}
counter++;
});
});
</script>
A demo is HERE

How to change HTML table cell by clicking and changing last change cell to original using JavaScript – (Switchboard)

I have a HTML table, and each cell has a value “Off”. When a user click on a cell I want to change that value of only that cell to “On” and if the user click another cell change it to “On” put the previously changed cell back to “Off”. Ie. Only one cell shows as “On” and all the others will be “Off”. This must be done using JavaScript and JQuery only (NOT angularJS)
<table id="switchboard-container">
<tbody>
<tr>
<td class="switch">Off</td>
<td class="switch">Off</td>
</tr>
<tr>
<td class="switch">Off</td>
<td class="switch">Off</td>
</tr>
</tbody>
</table>
Here is what I tried:
<script type="text/javascript">
$('#switchboard-container td').click(function ()
{
setClickHandlers();
});
function setClickHandlers() {
// Click handlers that change the content of switches to 'On' or 'Off'.
var cells = document.querySelectorAll('# switchboard -container td');
Array.prototype.forEach.call(cells, function (td) {
td.addEventListener('click', changeCell);
});
}
function changeCell() {
if (this.textContent == "On")
{
this.textContent == "Off";
}
else
{
this.textContent = "On";
}
}
</script>
I can change to “On” but I don’t know how to set other cells to “Off. Can some one please help?
Take a look at this fiddle:
https://jsfiddle.net/3fh4mLba/1/
Basically, adding $(".switch").text("Off"); will set the text to "Off" for all of them before you change it to on.
You can have a simple click handler to do this
$('#switchboard-container td.switch').click(function() {
var $this = $(this);
if ($this.hasClass('on')) { //if the current element is on then we can just make it off
$this.text('Off');
} else {
$this.text('On'); //make the current td on
$('#switchboard-container td.switch.on').removeClass('on').text('Off'); //make other td which are on as off
}
$this.toggleClass('on');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="switchboard-container">
<tbody>
<tr>
<td class="switch">Off</td>
<td class="switch">Off</td>
</tr>
<tr>
<td class="switch">Off</td>
<td class="switch">Off</td>
</tr>
</tbody>
</table>

get the value of any clicked td jquery

im traying to get the value of any clicked td and show this in a alert() window with jquery or javascript. I was trayin alote of code around the internet "googling" but anyone can do this but anyways i going to posted here...
$("table tbody").click(function() {
alert($(this).find('td.value').text());
});
$(document).ready(function() {
$('table tbody').find('tr').click(function() {
alert("row find");
alert('You clicked row ' + ($(this).index() + 1));
});
});
$(document).ready(function() {
$('table tbody').click(function() {
var i = $(this).index();
alert('Has clickado sobre el elemento número: ' + i);
});
});
$("table tbody").live('click', function() {
if $(this).index() === 1) {
alert('The third row was clicked'); // Yes the third as it's zero base index
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
<thead>
<tr>
<td>id</td>
<td>Nombre</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>miguel</td>
</tr>
</tbody>
</table>
Why not attach the click event directly to the td? You also need to make sure you're including jQuery...
$( "td" ).click(function() {
alert($(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<table border="1">
<thead>
<tr>
<td>id</td>
<td>Nombre</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>miguel</td>
</tr>
</tbody>
</table>
</body>
You need to include jQuery library to start working with it. Then just bind a click event to your td and you should see the alert pop up.
<head>
<title></title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js" type="text/javascript">
// Your code comes here
Also next time if something does not work, the first thing that you are supposed to so id open the console and check if you see any errors and act upon them.
Using console.log instead of alert should be the way to go as alert blocks the UI thread completely.
$("td").click(function() {
alert($(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table border="1">
<thead>
<tr>
<td>id</td>
<td>Nombre</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>miguel</td>
</tr>
</tbody>
</table>

Delete all rows from a table not having a specific text string

How can I delete all rows from a table which do not have a specific text in their column?
This does not work:
$('#mytable').find('tr:not(:has(th))').filter(
function() {
return $(this).find('td').text() != $("#some_component").val();
}).remove();
}
UPDATE
The answers posted do not work for me. Either they remove all rows (I need to check for the text in a specific row not the first one-or any row for that matter) or they do nothing.
The following which is a modification of my first attempt works though
$('#mytable').find('tr:not(:has(th))').filter(
function() {
return ($(this).find('td').text().indexOf($("#some_component").val()) < 0);
}
).remove();
HTML:
<table id="myTable">
<tr>
<td>Example One</td>
<td>Example Two</td>
<td>Example Three</td>
</tr>
<tr>
<td>Test One</td>
<td>Test Two</td>
<td>Test Three</td>
</tr>
<tr>
<td>Trial One</td>
<td>Trial Two</td>
<td>Trial Three</td>
</tr>
</table>
JavaScript jQuery (if it does contain):
$(document).ready( function() {
$('#myTable td:contains("Test")').parents("tr").remove();
});
JavaScript jQuery (if it does not contain):
$(document).ready( function() {
$('#myTable td').not(':contains("Test")').parents("tr").remove();
});
JSFiddle: http://jsfiddle.net/22QKM/
Out of interest, the code you posted does work, as far as I can tell. Here is a jsfiddle:
$(document).ready(function() {
$("#btn").click(function () {
console.log($("#some_component").val());
$('#mytable').find('tr:not(:has(th))').filter(
function() {
return $(this).find('td').text() != $("#some_component").val();
}).remove();
})
});
http://jsfiddle.net/EaNEd/
You can do this using below code.
$("td:not(contains("+$("#some_component").val()+")"))
.siblings()
.filter(":not(contains("+$("#some_component").val()+"))")
.parent('tr')
.remove();
Tested Code
$('tr').filter(function()
{
return $(this).find('td:contains("'+ $("#some_component").val() +'")').parent().css('background-color','red');
});
Test it and then replace .css() with .remove()
DEMO
Delete all rows from a table that does not having a specific text string:
function RemoveFromTable(tblID, VALUE){
$("#"+tblID).find(":not(:contains('"+VALUE+"'))").hide();
}
Note:You can also use "remove()" method instead of "hide()" method"
Call the function as follows:
RemoveFromTable('table ID','value')

Categories

Resources