How to get header cell name when dragging and dropping cell content - javascript

am here trying to perform drag and drop operations on cell data here what i want to do is,get the cell header name of the cell where am dropping content ,here am able to get cell header of that cell where am dragging content
this is the code am using for drag and drop functionality
<table id="#our_table" border="1">
<tr>
<th>head1</th>
<th>head1</th>
<th>head1</th>
</tr>
<tr><th>Row1<th>
<td><span class="event" id="a" draggable="true">aaa</span></td>
<td><span class="event" id="b" draggable="true">bbb</span></td>
<td></td>
</tr>
<tr>
<th>Row2<th>
<td></td>
<td></td>
<td></td>
</tr>
</table>
$(document).ready(function(){
$('.event').on("dragstart", function (event) {
var dt = event.originalEvent.dataTransfer;
dt.setData('Text', $(this).attr('id'));
});
$('table td').on("dragenter dragover drop", function (event) {
event.preventDefault();
if (event.type === 'drop') {
var data = event.originalEvent.dataTransfer.getData('Text',$(this).attr('id'));
if($(this).find('span').length===0){
de=$('#'+data).detach();
de.appendTo($(this));
}
};
});
})
fiddle for drag and drop functinality

I don't know whether it would be helpful to you or not but you can add that header's name as property for your td and then at time of drag&drop you can access that.
For Example.
<table id="#our_table" border="1">
<tr>
<th>head1</th>
<th>head1</th>
<th>head1</th>
</tr>
<tr>
<td><span class="event head1" id="a" draggable="true">aaa</span></td>
<td><span class="event head2" id="b" draggable="true">bbb</span></td>
<td><span class="head3"></span></td>
</tr>
<tr>
<td><span class="head1"></span></td>
<td><span class="head2"></span></td>
<td><span class="head3"></span></td>
</tr>
</table>
$(document).ready(function(){
$('.event').on("dragstart", function (event) {
var dt = event.originalEvent.dataTransfer;
dt.setData('Text', $(this).attr('id'));
var headName=$(this).attr('class').remove('event');
});
$('table td').on("dragenter dragover drop", function (event) {
event.preventDefault();
if (event.type === 'drop') {
var data = event.originalEvent.dataTransfer.getData('Text',$(this).attr('id'));
if($(this).find('span').length===0){
de=$('#'+data).detach();
de.appendTo($(this));
}
};
});
});

You can use index of current cell to fetch the header.
Here is my answer
$(document).ready(function () {
$('.event').on("dragstart", function (event) {
var dt = event.originalEvent.dataTransfer;
dt.setData('Text', $(this).attr('id'));
});
$('table td').on("dragenter dragover drop", function (event) {
event.preventDefault();
if (event.type === 'drop') {
var data = event.originalEvent.dataTransfer.getData('Text', $(this).attr('id'));
if ($(this).find('span').length === 0) {
de = $('#' + data).detach();
index = $(this).index();
headerText = $("table th").eq(index).text();
console.log(headerText);
alert(headerText);
de.appendTo($(this));
}
}
;
});
})
And here is working fiddle
http://jsfiddle.net/toLvzrLp/3/

Related

Bootstrap/JQuery Table Filter is not working

I can´t figure out why the filter is not working.
This is my input filed (which is the filter) an the table, both written in pug.
input#myInput.form-control(type='text', placeholder='Search..')
table.table.table-hover
thead
tr
th(scope='col') E-Mail
th(scope='col') Rolle
tbody#myTable
each user in users
tr
td #{user.local.email}
td #{user.local.role}
And here is the javascript document
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
Your are trying to filter table row <TR> and the content is inside <td> you need to check get by each <td> to find value
Try this :
$(document).ready(function(){
$("#myInput").on("keyup", function () {
var rows = $(".myTable").find("tr").hide();
if (this.value.length) {
var data = this.value.toLowerCase().split(" ");
$.each(data, function (i, v) {
rows.filter(":contains('" + v + "')").show();
});
} else rows.show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="myInput" placeholder="Search here" />
<table class="myTable">
<tr>
<td>lion</td>
</tr>
<tr>
<td>cat</td>
</tr>
<tr>
<td>dog</td>
</tr>
<tr>
<td>mouse</td>
</tr>
</table>

Get clicked column index from row click

I have a row click event. Recently had to add a checkbox to each row. How can I identify the clicked cell on row click event?
Or prevent row click when clicked on the checkbox.
Attempts: this.parentNode.cellIndex is undefined on the row click event.
function pop(row){
alert(row.cells[1].innerText);
}
<table style="width:100%">
<tr>
<th>Select</th>
<th>Site</th>
</tr>
<tr onclick="pop(this);">
<td><input type="checkbox" id="123456" /></td>
<td>Lonodn</td>
</tr>
</table>
Do you want something like this? You can just check the type attribute of the source element of the event and validate whether to allow it or not, you can stop the event using e.stopPropagation();return;.
function pop(e, row) {
console.log(e.srcElement.type);
if(e.srcElement.type === 'checkbox'){
e.stopPropagation();
return;
}else{
console.log(row);
alert(row.cells[1].innerText);
}
}
<table style="width:100%">
<tr>
<th>Select</th>
<th>Site</th>
</tr>
<tr onclick="pop(event, this);">
<td><input type="checkbox" id="123456" /></td>
<td>Lonodn</td>
</tr>
</table>
You should pass in the event details to your function and check the target property:
function pop(e){
// If the target is not a checkbox...
if(!e.target.matches("input[type='checkbox']")) {
alert(e.target.cellIndex);
}
}
<table style="width:100%">
<tr>
<th>Select</th>
<th>Site</th>
</tr>
<tr onclick="pop(event)">
<td><input type="checkbox" id="123456" /></td>
<td>Lonodn</td>
</tr>
</table>
Note: If you have nested elements inside the <td>, you might want to check e.target.closest("td") instead.
Note 2: You might need a polyfill for the matches method depending on which browsers you're supporting.
Here is an example if you don't want to attach a listener on every row :
document.getElementById("majorCities").addEventListener("click", function(e){
if(e.target.type === 'checkbox'){
var checked = e.target.checked;
var tr = e.target.parentElement.parentElement;
var city = tr.cells[1].innerHTML;
console.log(city+":checked="+checked);
}
});
<table id="majorCities" style="width:100%">
<tr>
<th>Select</th>
<th>Site</th>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>London</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>Paris</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>New-York</td>
</tr>
</table>
window.pop = function(row){
console.log('here');
var parent = row.parentNode;
Array.from(row.parentNode.querySelectorAll('tr')).forEach(function(tr, index){
if (tr === row) {
alert(index)
}
})
}
https://jsfiddle.net/sz42oyvm/
Here is for the pleasure, another example with an object containing the cities' names and a method to draw the table with ids corresponding to the name of the clicked city, so getting the clicked name is easier.
(function () {
var mySpace = window || {};
mySpace.cities = {};
mySpace.cities.pointer = document.getElementById("majorCities");
mySpace.cities.names = ["Select","City"];
mySpace.cities.data = [{"name":"Paris"},{"name":"New Delhi"},{"name":"Washington"},{"name":"Bangkok"},{"name":"Sydney"}];
mySpace.cities.draw = function(){
this.pointer.innerHTML="";
var html = "";
html+="<tr>"
for(var i=0;i < this.names.length;i++){
html+="<th>"+this.names[i];
html+="</th>"
}
html+="</tr>"
for(var i=0;i < this.data.length;i++){
html+="<tr>"
html+="<td><input id='"+this.data[i].name+"' type='checkbox'/></td>"
html+="<td>"+this.data[i].name+"</td>"
html+="</tr>"
}
this.pointer.innerHTML=html;
}
mySpace.cities.draw();
mySpace.cities.pointer.addEventListener("click", function(e){
if(e.target.type === 'checkbox'){
var checked = e.target.checked;
var city = e.target.id;
console.log(city+":checked="+checked);
}
});
})();
table {width:25%;background:#ccc;border:1px solid black;text-align:left;}
td,tr {background:white;}
th:first-of-type{width:20%;}
<table id="majorCities">
</table>

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();
});

tr on click change to different tr

Using Jquery, I have a table and on clicking the table row i want td to change to textbox or dropdown.
After entering the values of textbox i want those values to be updated to that table row on which it was clicked. I have got it partially.
Please help me with this.
This is my html code:
<table id="myTable" >
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
This is my script:
$(document).ready(function () {
$("#myTable").children("tbody").children("tr").children("td").click(function () {
$(this.parentNode).replaceWith('<tr><td ><textarea></textarea></td><td ><textarea></textarea></td><td ><textarea></textarea></td></tr>').appendTo($(this)).val().select().blur(function () {
var newText = $(this).val();
$(this).parent().text(newText);
});
});
});
Try something like this. I don't check if it compile, it is just an idea:
$("#myTable").children("tbody").children("tr").children("td").click(function () {
var cell1Text = $(this).find('.cell1').text();
$(this.parentNode).replaceWith('<tr><td><textarea class="cell1">'+cell1Text+'</textarea></td>...</tr>').appendTo($(this)).val().select().blur(function () {
var newText = $(this).val();
$(this).parent().text(newText);
});
})
.blur(function () {
var cell1Val = $(this).find('.cell1').val();
$(this.parentNode).replaceWith('<tr class="cell1">'+cell1Val+'<td ></td>...</tr>').appendTo($(this)).val().select().blur(function () {
var newText = $(this).val();
$(this).parent().text(newText);
});
});

How to keep adding data to next table column

This Fiddle Example shows a comparison table that dynamically shows information in a column when a button is clicked. Once the table is filled up, I want to start the whole process again. But as the example shows, the buttons are stuck at adding information to th:nth-child(2) and td:nth-child(2) during the second time instead of moving on to the next column like during the first time.
I'm guessing this part needs some change if( allCells === fullCells ) { to keep information being added to next columns.
HTML
<div class="area">
<button>Gah</button>
</div>
<div class="area">
<button>Kaj</button>
</div>
<div class="area">
<button>Fdw</button>
</div>
<div class="area">
<button>ffdf</button>
</div>
<table>
<thead>
<tr>
<th>Placeholder</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>Age</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Name</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Race</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Nationality</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Education</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Language</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Code:
$(function() {
$('.area').each(function(){
var area = $(this),
filltable ='',
button = $(this).find('button'),
buttontext = button.text();
button.on("click",function(){
var allCells = $('table').find('th,td').length;
var fullCells = $('table').find('th,td').filter(function() {
return $(this).text() != '';
}).length;
if( allCells === fullCells ) { // If table is full
$('table').find('th,td').not(':first-child').removeClass('addinfo');
filltable();
}
else { // If table isn't full
filltable = function(){
var i = $('th.addinfo').length !== 0 ? $('th.addinfo:last').index() : 0;
console.log( i );
i + 2 > $('th').length ||
$('th,td').filter(':nth-child(' + (i + 2) + ')')
.addClass( 'addinfo' ).html(buttontext);
}
filltable();
}
}); // end button on click function
});
});
Please see the attached link for demo. I have created a function name cleartable() which clears the table if its full and have used your old filltable() function to repopulate. There is repetition of code which you will have to clean up.
th:nth-child(2) identifies second child of th.
td:nth-child(2) identifies second column.
Similarly if you wanted to do something with let say second row, you can use tr:nth-child(2).
I hope this helps you understand a little about parent-child relationship in jquery.
JSFIDDLE DEMO
function clearTable() {
$('table th:nth-child(2)').html('');
$('table th:nth-child(3)').html('');
$('table th:nth-child(4)').html('');
$('table td:nth-child(2)').html('');
$('table td:nth-child(3)').html('');
$('table td:nth-child(4)').html('');
}
http://jsfiddle.net/jqVxu/1/
I think you'd better to count th only. count all td and th make me confused.
$(function () {
function filltable(buttontext) {
var i = $('th.addinfo').length !== 0 ? $('th.addinfo:last').index() : 0;
i + 2 > $('th').length || $('th,td').filter(':nth-child(' + (i + 2) + ')')
.addClass('addinfo').html(buttontext);
}
$('.area').each(function () {
var area = $(this),
button = $(this).find('button'),
buttontext = button.text();
button.on("click", function () {
var allCells = $('table').find('th').length-1;
var fullCells = $('table th.addinfo').length;
console.log(allCells, fullCells);
if (allCells === fullCells) { // If table is full
$('table .addinfo').removeClass('addinfo');
filltable(buttontext);
} else { // If table isn't full
filltable(buttontext);
}
});
});
});

Categories

Resources