I would like the following script to move a table row to the top of a table. I can't figure out how to reference the id of the first row, however, since the ID is set dynamically, I tried row.insertAfter(row.first()); but it's making the row disappear instead of moving it. Any ideas how to reference the top row?
$(".top").click(function(){
var row = $(this).parents("tr:first");
if ($(this).is(".top")) {
row.inserAfter(row.first());
} else {
return false;
}
});
<tbody id="sortable">
<tr id="row1">
<td>Top</td>
</tr>
<tr id="row2">
<td>Top</td>
</tr>
<tr id="row3">
<td>Top</td>
</tr>
</tbody>
This works...
$(".top").click(function() {
var thisRow = $(this).parent().parent();
var firstRow = thisRow.parent().find("tr:first").not(thisRow);
thisRow.insertBefore(firstRow);
});
$(".top").click(function(){
var tr=this.parentNode.parentNode;
tr.parentNode.insertBefore(tr.parentNode.firstChild,tr);
tr.parentNode.removeChild(tr);
}
Do you wanna do something like this?
$(".top").click(function(){
var $this = $(this); // make a reference to the current element
$.ajax({
url: 'your/ajax/url.php',
success: function(data) {
// do what you want with data,
// and then move the row on top
// of the table, like so
var row = $this.parents("tr");
var first_row = row.parent().find('tr:first');
if (row && first_row && row != first_row) {
row.insertBefore(first_row);
}
}
});
return false; // stay on the page
});
Check http://api.jquery.com/jQuery.ajax/ for more info
var row = $(this).find("tr").eq(0);
Related
I have a table that I'm filtering by using a select option, but I can't figure out how to go back and show all data after the initial filter. Also I need help drying my code.
// SHOWS INDIVIDUAL FILTER BUT CAN'T SHOW ALL
$(document).ready(function($) {
$("#sortAwardType").change(function() {
$("table").show();
var selection = $(this).val().toUpperCase();
var dataset = $(".awards-body").find("tr");
dataset.show();
if(selection) {
dataset.filter(function(index, item) {
// Filter shows table row with the word 'General'
return $(item).find(":contains('General')").text().toUpperCase().indexOf(selection) === -1;}).hide();
} else {
// .all corresponds to a "Show All" option. When selected the data doesn't show
$("#sortAwardTable").change(function(){
$(".all").dataset.show();
});
}
});
});
// ATTEMPTING DRY CODE. NOW I CAN'T FILTER AT ALL
$(document).ready(function($) {
$("#sortAwardType").change(function() {
$("table").show();
var selection = $(this).val().toUpperCase();
var dataset = $(".awards-body").find("tr");
var match = [
":contains('General')",
":contains('Free')",
":contains('Regional')",
":contains('Demographic')"];
dataset.show();
if(selection) {
dataset.filter(function(index, item) {
return $(item).find(match).text().toUpperCase().indexOf(selection) === -1;}).hide();
} else {
// .all corresponds to a "Show All" option. When selected I want all data to show but instead it only shows an empty table (header present but no rows)
$("#sortAwardTable").change(function(){
$(".all").dataset.show();
});
}
});
});
I don't want to keep repeating the if block only to change the ":contains('_____')". I tried grouping them in an array and assigning them to var match, but then the filter doesn't work.
salam , you have just to put all contains selectors in the same string
$(item).find(":contains('General'),:contains('Free'),:contains('Regional'),:contains('Demographic')").
but if you want take it easy follow my ex:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="searchBox">
<table id='testTable'>
<tr >
<td>aa</td>
<td>bb</td>
<td>cc</td>
</tr>
<tr >
<td>ab</td>
<td>bc</td>
<td>cd</td>
</tr>
<tr >
<td>zz</td>
<td>ee</td>
<td>ff</td>
</tr>
</table>
<script>
$('#searchBox').keyup(function(){
var val = $(this).val().toLowerCase();
if(val ===""){
$("#testTable > tbody > tr").toggle(true);
return;
}
$("#testTable > tbody > tr").toggle(false);
$("#testTable").find("td").each(function(){
if($(this).text().toLowerCase().indexOf(val)>-1)
$(this).parent().toggle(true);
});
});
</script>
actually i am making a todolist so i want to replace div which i added through in innerhtml with tr and after created of the first row in html please check
Html Part:
<table id="ws-table" class="table table-bordered">
<tr id="insert">
<th>#</th>
<th>Date</th>
<th>Items</th>
<th>Edit / Delete</th>
</tr>
<!-- Here i wanted an tr
</table>
actually i am making a todolist so i want to replace div which i added through in innerhtml with tr and after created of the first row in html please check
javascript part :
var takeInput;
var DATA = [];
load();
function insertItem(){
takeInput = document.getElementById('item').value;
DATA.push(takeInput);
renderJson(DATA);
document.getElementById('item').value = "";
}
function renderJson(data){
document.getElementById('container').innerHTML = "";
for(var i in data){
container.innerHTML = container.innerHTML + "<div id=" + i + " onclick='removeItem(this.id)'><input type='checkbox'/><label>"+data[i]+"</label></div>";
}
save();
}
function removeItem(Id){
var itemId = document.getElementById(Id);
if(itemId.childNodes[0].checked == true){
var arr_ind = DATA.indexOf(itemId.childNodes[1].innerText);
DATA.splice(arr_ind,1);
itemId.parentNode.removeChild(itemId);
save();
}
}
function save(){
localStorage.myList = JSON.stringify(DATA);
}
function load(){
DATA = JSON.parse(localStorage.myList);
renderJson(DATA);
}
Element.innerHTML is for replacement only, so you need to read it first concatenate with new row and then assing back, better use Element.insertAdjacentHTML():
var row = "<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>";
document.querySelector("#ws-table tbody").insertAdjacentHTML("beforeend", row);
You may want to use thead for your table header. Check this thread for more information.
I'm trying to run through a table and change each cell based on the row. Table example:
<table id='myTable'>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
</table>
Function example (in script under body):
function myFunction(){
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = r.find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = c.getChild();//attempt to get the div in the td
square.innerHTML='html here';
});
}
});
}
$(document).load(myFunction);
The example shown is non-specific version of the actual function I'm trying to run.
To be clear, I have linked to the jQuery 2.1 CDN, so the page should be able to read jQuery.
Console shows no errors, but still does not run appear to run the function. Checking the tested row in the console shows no change to the html in the div. Any advice for this?
When I run it I get an error on r.find() because .find() is a jQuery function and needs to be called on a jQuery object, which r is not. Simply wrapping it in a $() works.
function myFunction(){
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = $(r).find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = c.getChild();//attempt to get the div in the td
square.innerHTML='html here';
});
}
});
}
https://jsfiddle.net/k50o8eha/1/
You may need to do asomething similar to the c.getChild();
Here's a simplified version :
$("#myTable tr").each(function(i, r){
if(i==1)
{
$(this).find('td').each(function()
{
$(this).find("div").html("html here");
});
}
});
Example : https://jsfiddle.net/DinoMyte/4dyph8jh/11/
Can you give this a try...
$( document ).ready(function() {
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = r.find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = c.getChild();//attempt to get the div in the td
square.innerHTML='html here';
});
}
});
});
or shorthand...
$(function() {
});
$( document ).ready(function() {
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = $(r).find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = $(c).children('div');
square.text('html here');
});
}
});
});
table{
background-color: #eee;
width: 300px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='myTable'>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
</table>
This works, you can try this
JSBIN
function myFunction(){
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i){
if(i==1){//to edit second row, for example
$(this).find('td').each(function(j){
$(this).find('div').html('html here');
});
}
});
}
$(document).ready(myFunction);
first the "id" should be unique to an element... but ok, this should do the trick:
$(document).ready(function(){
$("#myTable>tr:odd").children("div").text('html here');
});
If you want to put html code in the div, change text for html. if you want to specify the row then:
$(document).ready(function(){
myRow = //set its value...
$("#myTable>tr").each(function(idx, element){
if(idx == myRow){
element.children("div").text('html here');
}
}, myRow);
});
I have a table which will output the id of the parent cell when it is clicked. How could I change this so it outputs more than one clicked cell. For example, right now if I click cell id '1' it will output 1. If I click cell '2' it will output 2 and so on. How can I make it so that it outputs '1,2,3' given that I've clicked on cell 1, 2 and 3.
HTML:
<table>
<tr>
<td class='test' id='1'><img src='images/Dog.gif'/></td>
<td class='test' id='2'><img src='images/Cat.gif'/></td>
<td class='test' id='3'><img src='images/Mouse.gif'/></td>
<td class='test' id='4'><img src='images/Human.gif'/></td>
</tr>
</table>
<div id='output'></div>
JS:
$(document).ready(function() {
$('td.test').click(function() {
$('#output').text(this.id);
});
});
Also, is there a way that if I clicked back on say, cell 2. it would remove '2' from the list.
Use an array to keep track of clicked items:
$(document).ready(function() {
var clicked = [];
$('td.test').click(function() {
var found = clicked.indexOf(this.id);
// Remove
if(found !== -1) {
clicked.splice(found, 1);
// Add
} else {
clicked.push(this.id);
}
$('#output').text(clicked.join(','));
});
});
http://jsfiddle.net/mx2kj/
var ids = "";
$(".test").on("click", function () {
$(this).data("selected", !$(this).data("selected"));
var ids = $(".test").filter(function () {
return $(this).data("selected") === true;
}).map(function () {
return this.id;
}).get().join(",");
alert(ids);
});
Demo: http://jsfiddle.net/fY5tj/1
You can append your clicked item id in your output div like this :
$('td.test').click(function() {
var currentText = $("#output").text();
$("#output").text(currentText+this.id);
});
I have a table that is a history of a mysql record.
I want to add a button that will highlight the changes.
<table>
<tr>
<td>100</td>
<td>200</td>
<td>300</td>
</tr>
<tr>
<td>100</td>
<td>200</td>
<td>600</td>
</tr>
</table>
In this example the 600 would be highlighted as it was 300 and is now 600.
UPDATE: Thanks, I should have said there would be more than 2 rows. could be upto 20 rows
This jsFiddle shows an example that will iterate over a table of any size and highlight the cells that have changed from the previous row.
$(function() {
var $rows = $("tr");
for (oldIndex = 0; oldIndex < $rows.length-1; oldIndex++) {
var newIndex = oldIndex + 1;
var $oldCols = $("td", $rows[oldIndex]);
var $newCols = $("td", $rows[newIndex]);
for (col = 0; col < $oldCols.length; col++) {
var $newCol = $($newCols[col]);
if ($($oldCols[col]).html() != $newCol.html()) {
$newCol.addClass("highlight");
}
}
}
});
Your solution should go along these lines. Assuming set1 and set2 are id's of two trs here is a sample code (not tested).
var s1 = $('tr#set1 td');
var s2 = $('tr#set2 td');
var l = $('tr#set1 td').length;
for(var i =0; i<l i++){
if(s1.eq(i).text() != s2.eq(i)){
$(s2.eq(i)).highlight();
}
}
$('table tr.new td').each(function(i){
//First TR td, Previous Rows
td = $(this);
check = $('table tr.prev td:eq('+i+')');
if(td[0].innerText != check[0].innerText)
{
check.addClass('Changed');
}
})
This should do it but you need to add 2 classes:
<table>
<tr class="new">
<td>150</td>
<td>200</td>
<td>300</td>
</tr>
<tr class="prev">
<td>100</td>
<td>200</td>
<td>600</td>
</tr>
</table>
Demo: http://jsfiddle.net/hjXZd/1/
Hope this helps.
I advise you to do an attr for each TD and place the mysql id in there so that you will only compare the rows that are the same in the DB, otherwise if your first list has more items then the second list the results will be corrupt.
Assuming your table has the id results, here is a solution:
var topRow = $('table#results tr:eq(0)');
var bottomRow = $('table#results tr:eq(1)');
topRow.find('td').each(function(index,item){
var shadow = bottomRow.find('td:eq('+index+')');
if($(item).contents().text()!=shadow.contents().text()){
shadow.css({'background':'yellow'});
}
});
Update: this solution compares the top row with all following ones:
$('table#results tr:eq(0) td').each(function(index,item){
var orig = $(item).contents().text();
$('table#results tr:gt(0)').find('td:eq('+index+')').each(function(index2,item2){
var shadow = $(item2);
if(orig!=shadow.contents().text()){
shadow.css({'background':'yellow'});
}
});
});
Using Jquery .live you can handle multiple elements.
See here
http://api.jquery.com/live/
You have to give ids for the changed values.. which can be inside divs.
Hope td also may work
On button click using this .live you can chnage style of div
like highlighting.
Use addClass function os jquery itslef or you can add css using jquery add