jquery replace td contents - javascript

i've searched for answers to my question with partial success but unfortunately the answer i found only changes one field not ALL fields.
I have a table on my website as follows:
<table>
<tr>
<td>1</td>
<td id="demand">DL-001</td>
<td>Description 1</td>
</tr>
<tr>
<td>2</td>
<td id="demand">DL-002</td>
<td>Description 2</td>
</tr>
<tr>
<td>3</td>
<td id="demand">DL-003</td>
<td>Description 3</td>
</tr>
</table>
This is generated by a PHP script, querying the details from a MySQL database.
What I would like to do is use jQuery to replace each of the following:
<td id="demand">DL-001</td>
with
<td id="demand">DL-001</td>
Any help would be greatly appreciated!
Edit: Added jQuery from OP's comment:
$(".demand").text('text'); replaces all tds with class "demand" contents to 'text'.
However when I use the following, it does not work:
$(".demand").text('<a href=\'order.php?d=' + data[2] + '\'>' + data[2] + '</a>');

Change your ID's to classes - ID's in a DOM must be unique, and will cause problems with most javascript.
Below is a working snippet, with the IDs changed, and sample jQuery that could be used to accomplish this.
// no-conflict safe document ready
jQuery(function($) {
// loop over all td's with the class of demand
$('td.demand').each(function() {
// load the DL-XXX into a variable (since it's used more than once)
var dl = $(this).text();
// change the td html to the link, referencing the DL-XXX number
$(this).html('' + dl + '');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>1</td>
<td class="demand">DL-001</td>
<td>Description 1</td>
</tr>
<tr>
<td>2</td>
<td class="demand">DL-002</td>
<td>Description 2</td>
</tr>
<tr>
<td>3</td>
<td class="demand">DL-003</td>
<td>Description 3</td>
</tr>
</table>

To achieve expected result, use below option of using jquery append
$(".demand").each(function(){
var val = $(this).text()
$(this).html(''+val+'')
})
https://codepen.io/nagasai/pen/zWxbqK

Try this:
(function($) {
var demands = $(".demand");
demands.each(function() {
// Make sure to strip-off redundant calls to $(this)
// Calling $(this) once suffices
var el = $(this),
txt = el.text();
el.html($("<a>", {href: 'order.php?d='+txt, text: txt}));
});
})(jQuery);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<table>
<tr>
<td>1</td>
<td class="demand">DL-001</td>
<td>Description 1</td>
</tr>
<tr>
<td>2</td>
<td class="demand">DL-002</td>
<td>Description 2</td>
</tr>
<tr>
<td>3</td>
<td class="demand">DL-003</td>
<td>Description 3</td>
</tr>
</table>
</body>
</html>

Related

Delete All Rows in Table except the header row

Using Javascript (with JQuery), I would like to delete all rows in a table except the header row.
This seems like a simple thing because I see quite a few posts on StackOverFlow about this and a lot of solutions provided and accepted. But, none of them seem to work for me. Please refer to my code below:
function delTable() {
console.log("Delete all rows, but the header");
// Option-A
// $('#TableA tbody tr').remove();
// Option-B
// Accepted answer for: https://stackoverflow.com/questions/9420203/how-to-remove-all-rows-of-the-table-but-keep-the-header
// $('#TableA tr').not(function(){ return !!$(this).has('th').length; }).remove();
// Option-C
$('#TableA tbody').empty();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body onLoad="delTable();">
<table id="TableA">
<th>
<tr>
<td>Col A</td>
<td>Col B</td>
</tr>
</th>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</tbody>
</table>
</body>
</html>
Does any one know what I am doing wrong? Thanks.
-Karthik
Just update your th to thead and you good to go, see below:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.js"></script>
</head>
<body onLoad="delTable()">
<table id="TableA">
<thead>
<tr>
<td>Col A</td>
<td>Col B</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</tbody>
</table>
</body>
</html>
JS:
function delTable() {
console.log("Delete all rows, but the header");
// Option-A
// $('#TableA tbody tr').remove();
// Option-B
// Accepted answer for: https://stackoverflow.com/questions/9420203/how-to-remove-all-rows-of-the-table-but-keep-the-header
// $('#TableA tr').not(function(){ return !!$(this).has('th').length; }).remove();
// Option-C
$('#TableA tbody').empty();
}
Working fiddle:
https://jsfiddle.net/pvfkxdby/1/
You need to replace th with thead and use $('#TableA tbody').find("tr") as follows:
function delTable() {
console.log("Delete all rows, but the header");
$('#TableA tbody').find("tr").remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body onLoad="delTable();">
<table id="TableA">
<thead>
<tr>
<td>Col A</td>
<td>Col B</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</tbody>
</table>
</body>
</html>
This worked for me. You set apart your header with <th> instead of <thead> and then you had <td> in your header instead of <th>.
$(document).ready(() => {
$("#delete").click(() => {
$("#TableA tbody tr").remove()
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="TableA">
<thead>
<tr>
<th>Col A</th>
<th>Col B</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</tbody>
</table>
<button id="delete">delete</button>
By inspecting your HTML in my Google Chrome I can see that the rows were rearranged so that even the first line is inside <tbody> tag. Therefore the whole table is removed. You can fix this simply by wrapping the first row in <thead> tag or use different approach which does not use <tbody> tag.
That would be a simple one-liner:
function delTable() {
console.log("Delete all rows, but the header");
$('#TableA').find("tr:not(:first)").remove(); // Code to remove all rows in table except the header row
}
What the given code does is identify the rows in the table 'TableA' that is not the first row using the command: $('#TableA').find("tr:not(:first)") and subsequently remove the rows using the .remove() command.

How to remove a pattern of table row elements from a table?

If I have the following table, which I can't manually touch, but can apply javascript to...
<table data="customTable">
<tr>
<td>item 1</td>
</tr>
<tr>
<td height="10"></td>
</tr>
<tr>
<td>item 2</td>
</tr>
<tr>
<td height="10"></td>
</tr>
</table>
...when the DOM loads fully, how can I remove every instance of <tr><td height="10"></td></tr> from the above table via jQuery or raw JavaScript? I don't need that row at all and its causing design issues for me. This is my first time trying to learn how to replace a full pattern of elements.
Hopefully, this is doable via JavaScript?
This should do the trick.
jQuery
$('td[height="10"]').parent().remove();
https://jsfiddle.net/uzv3fn2e/1/
Vanilla JS
Array.from(document.querySelectorAll('td[height="10"]')).forEach(td => td.parentNode.remove());
https://jsfiddle.net/t7y6aqc5/
You can use :has() selector to select tr that has td with specific attribute
$("tr:has(td[height='10'])").remove()
$("tr:has(td[height='10'])").remove()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table data="customTable">
<tr>
<td>item 1</td>
</tr>
<tr>
<td height="10"></td>
</tr>
<tr>
<td>item 2</td>
</tr>
<tr>
<td height="10"></td>
</tr>
</table>
without using jquery javascript has also remove()
document.querySelectorAll("td").forEach(el => el.getAttribute("height") === "10" && el.parentNode.remove())
<table data="customTable">
<tr>
<td>item 1</td>
</tr>
<tr>
<td height="10"></td>
</tr>
<tr>
<td>item 2</td>
</tr>
<tr>
<td height="10"></td>
</tr>
</table>

Get Data from HTML Table with Jquery (Or other ways if possible)

I have a really big HTML Table with data formatted like this (a simplified version of my table):
https://pastebin.com/K5UB4cGB
The list is much bigger.
I need to know which Application runs on which Server(multiple).
I now need to somehow get all the data and store it (maybe in an array) so I can work with it.
(For example I need to compare certain applications and write a code to document it.)
I've already tried many methods I found on the web but I not sure im working in the right way.
My recent atempt is:
var data = Array();
$("table").each(function(i, v) {
data[i] = Array();
$(this).each(function(ii, vv) {
data[i][ii] = $(this).text();
});
})
document.write(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</table>
<div id="result" style="color: #f00"></div>
Outputs:
1 2 3 4 6 7 8 9 10
With this method I get one array:
1,2,3,4,5,6,7,8,9,10
But I cannot access the stored vaules because for example data[0] outputs all the values and not only one.
Sorry for the long text
Thanks for your help :)
Kind Regards,
Markus
You can try using nested for loops and get a nested array of data.
let data = [];
$("table tr").each(function() {
let row = [];
$(this).children("td").each(function() {
row.push($(this).text());
})
data.push(row);
})
console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>6</td>
<td>7</td>
</tr>
<tr>
<td>8</td>
<td>9</td>
<td>10</td>
</tr>
</table>
You need to iterate rows and within rows iterate cells
You can do this all with map()
var data = $('tr').map(function() {
return [$(this).children().map(function() {
return $(this).text().trim()
}).get()];
}).get();
console.log(JSON.stringify(data));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>6</td>
<td>7</td>
</tr>
<tr>
<td>8</td>
<td>9</td>
<td>10</td>
</tr>
</table>
<div id="result" style="color: #f00"></div>
use each to loop through td and get its text value
var val=[]
$('#table td').each(function(e){
val.push($(this).text())
})
console.log(val)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<table id="table">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>6</td>
<td>7</td>
</tr>
<tr>
<td>8</td>
<td>9</td>
<td>10</td>
</tr>
</table>
In the following I am using an each function to derive the data of the table and then pushing into an array list. I hope this code is helpful. This code is really small.
var arr = [];
$("th, td").each(function(){
arr.push($(this).text());
$("#result").text(arr);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>6</td>
<td>7</td>
</tr>
<tr>
<td>8</td>
<td>9</td>
<td>10</td>
</tr>
</table>
<div id="result" style="color: #f00"></div>

jQuery Replace not acting as expected

$(".rowIWanTtoReplace").replaceWith("<tr><td rowspan='11' class='n'>n</td><td rowspan='8'>n</td><td>t</td><td>n</td></tr><tr><td>u</td><td>n</td></tr><tr><td>v</td><td>n</td></tr><tr><td>w</td><td>n</td></tr><tr><td>x</td><td>n</td></tr><tr><td>y</td><td>n</td></tr><tr><td>z</td><td>n</td></tr>");
td {
border: 1px solid black
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table class="station-device-table4">
<tr>
<td>x</td>
<td>y</td>
<td>z</td>
</tr>
<tr class="rowIWanTtoReplace">
<td rowspan="11" class="s">foobar</td>
<td rowspan="7">foobar</td>
<td>n</td>
</tr>
</table>
I just wanted to check whether or not this should be the result of a replaceWith() in this situation:
If I have a table and on one row I apply replaceWith(), And What I replace it with is multiple table rows.
Shouldn't that just affect the HTML so when displayed multiple should show in that section?
i.e ------ TR 1 -----------
.replaceWith("<tr>x</tr><tr>y</tr>")
shouldn't the first row replace the other row. And the second row append after?
Or is there an alternative method?
Thanks.
Example code for situation:
<table class="station-device-table4">
<tr>
<td>x</td>
<td>y</td>
<td>z</td>
</tr>
<tr class="rowIWanTtoReplace">
<td rowspan="11" class="s">foobar</td>
<td rowspan="7">foobar</td>
<td>n</td>
</tr>
</table>
JQuery example:
$(".rowIWanTtoReplace").replaceWith("<tr>
<td rowspan="11" class="n">n</td>
<td rowspan="8">n</td>
<td>t</td>
<td>n</td>
</tr>
<tr><td>u</td><td>n</td></tr>
<tr><td>v</td><td>n</td></tr>
<tr><td>w</td><td>n</td></tr>
<tr><td>x</td><td>n</td></tr>
<tr><td>y</td><td>n</td></tr>
<tr><td>z</td><td>n</td></tr>")
Note: This is made from backbone collections and stuff. I have outputted to the screen the html that it using to update. And put the code together as if it was normal jquery.
You cannot have linefeeds in strings unless you use template literals - also you had nested double quotes which also does not work.
In the original code you replaced a header cell with a table row which also did not compute.
This might be what you want:
$(".rowIWanTtoReplace").replaceWith(`<tr>
<td rowspan="11" class="tvmStatus">TVM Status</td>
<td rowspan="8">Component Events</td>
<td>t</td>
<td>n</td>
</tr>
<tr><td>u</td><td>n</td></tr>
<tr><td>v</td><td>n</td></tr>
<tr><td>w</td><td>n</td></tr>
<tr><td>x</td><td>n</td></tr>
<tr><td>y</td><td>n</td></tr>
<tr><td>z</td><td>n</td></tr>`)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="station-device-table4">
<tr>
<td>x</td>
<td>y</td>
<td>z</td>
</tr>
<tr class="rowIWanTtoReplace">
<td rowspan="11" class="s">foobar</td>
<td rowspan="7">foobar</td>
<td>n</td>
</tr>
</table>

Complete replace of a cel in HTML table

I have something like this:
<table id="myTable">
<tr>
<td class="1">cell 1</td>
<td class="2">cell 2</td>
</tr>
<tr>
<td class="3">cell 3</td>
<!-- from here -->
<td class="4">cell 4</td>
<!-- to here -->
</tr>
</table>
What I need is to replace the all the code from cell 4 in JavaScript, I mean replace
<td class="4">cell 4</td>
with
<td id="8" class="3" title="important">cell 4</td>
I tried this:
var cell = document.getElementById("myTable").rows[1].cells;
cell[1] = newCode;
function myFunction() {
var h1 = document.getElementsByClassName("4")[0];
var atttittle = document.createAttribute("tittle");
atttittle.value = "important";
h1.setAttributeNode(atttittle);
var attid = document.createAttribute("id");
attid.value = "8";
h1.setAttributeNode(attid);
var attclass = document.createAttribute("class");
attclass.value = "3";
h1.setAttributeNode(attclass);
var element=document.getElementById("8");
alert(element.outerHTML);
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table id="myTable">
<tr>
<td class="1">cell 1</td>
<td class="2">cell 2</td>
</tr>
<tr>
<td class="3">cell 3</td>
<td class="4">cell 4</td>
</tr>
</table>
<button onclick="myFunction()">Click here replace </button>
</body>
</html>
sorry for previous answer.I changed to JavaScript
You could use JQuery for that. something like this: http://api.jquery.com/replacewith/
Hope it helps
EDIT:
In your example you could use something like this:
$( ".4" ).replaceWith( "<td id="8" class="3" tittle="important">cell 4</td>" );

Categories

Resources