Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have the follow code:
for (var key in returns) {
$('#tBodyTable').append('\
<tr>\
<td >\
<label>'+ returns[key].name +'</label>\
</td>\
<script>\
for (var i in quant_colums){\
document.write("<td ><center><label>a</label></center></td>");\
};\
</script>\
</tr>\
');
};
This code are inside the return of Jquery Ajax, and the first loop overwrite the body the table dynamically. The second loop is for create <td> dynamically based the value of the variable quant_columns, that is why has a javascript there. But I don't know how exactly to do this. Each line of the table will have a number of the columns in determined point, based the result of the query.
How I can do it?
For this case, you do not need to insert a script tag, you can do everything you need in the same function.
$(function(){
var returns = {t1: {name:'teste1'},t2:{name:'teste2'},t3:{name:'teste2'}};
var quant_colums = 3;
var $table = $('#tBodyTable');
for (var key in returns) {
var $tr = '<tr>\
<td >\
<label>'+ returns[key].name +'</label>\
</td>\
</tr>';
for (var i in quant_colums){
$tr.append("<td ><center><label>a</label></center></td>");
}
$table.append($tr);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<table id="tBodyTable"></table>
You can use the DOM to insert elements dynamically based on the data you have like this.
var returns, quant_colums, tbody;
returns = {
a: {name: "a"},
b: {name: "b"},
c: {name: "c"}
};
quant_colums = [0, 1, 2, 3];
tbody = window.document.querySelector("#tBodyTable");
Object.keys(returns).forEach(function (key) {
var row, cell;
row = tbody.insertRow();
cell = row.insertCell();
cell.innerHTML = '<label>' + returns[key].name + '</label>';
quant_colums.forEach(function (i) {
cell = row.insertCell();
cell.innerHTML = "<center><label>" + i + "</label></center>";
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="script.js"></script>
</head>
<body>
<table>
<tbody id="tBodyTable"></tbody>
</table>
</body>
</html>
Related
I'm trying to get the data from a datatable. I know that i can use datatable.data() but my cells have html data inside so I get something like this:
0:
CIF: "<span class='text-success font-weight-bold'>B81692097</span>"
CODIGO CURSO: "<div class='d-flex justify-content-center'><i data-toggle='tooltip' data-type='CODIGO CURSO' data-placement='top' title='Rellenar celda' class='empty-cell editable-data material-icons text-info'>keyboard</i></div>"
CODIGO USUARIO: "12345678-A"
DT_RowId: "row_1"
EDITORIAL: "CONZEPTO"
FACTURABLE: "<i class='material-icons text-success'>check_circle</i>"
FECHA ACTIVACION: 43831
HORAS: 1
LICENCIA: "-"
NOMBRE CENTRO: "<span class='text-success font-weight-bold'>ACADEMIA LIDER SYSTEM S.L.</span>"
NOMBRE CURSO: "<div class='d-flex justify-content-center'><span data-type='NOMBRE CURSO' class='editable-data text-info font-weight-bold'>Marketing y cosas</div>"
NOMBRE USUARIO: "Jose Perez Perez"
PERFIL: "-"
PRECIO: 1
REFERENCIA: "<div class='d-flex justify-content-center'><i data-toggle='tooltip' data-type='REFERENCIA' data-placement='top' title='Rellenar celda' class='empty-cell editable-data material-icons text-info'>keyboard</i></div>"
URL: "<span class='text-success font-weight-bold'>campusonline.lidersystem.com</span>"
VALIDADO: "↵ <span class='d-none orderable-value'>2</span>↵ <i data-toggle='tooltip
And, for example, from CIF I want to get B81692097 instead of <span class='text-success font-weight-bold'>B81692097</span>
I know that I could make a function to get the specific data from every cell but I wonder if there is an easier way to do this, I have been searching in the docs but I couldnt find anything.
Is there any way to get this with the tools that datatable offers?
Thank you guys
Depending on what specific data you need, here are some examples in a stand-alone demo you can run for yourself.
This includes an example showing the removal of HTML tags from cell data.
The demo table:
To see the results, uncomment the relevant console.log() statement(s). The browser console (F12) will show the output:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Iterate Cells</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
</head>
<body>
<div style="margin: 20px;">
<table id="demo" class="display dataTable cell-border" style="width:100%">
<thead>
<tr><th>Column One</th><th>Column Two</th></tr>
</thead>
<tbody>
<tr><td>alfa</td><td class="foo">bravo</td></tr>
<tr><td class="foo">charlie</td><td>delta</td></tr>
<tr><td>echo</td><td><b>foxtrot</b></td></tr>
</tbody>
</table>
</div>
<script type="text/javascript">
$(document).ready(function() {
var table = $('#demo').DataTable({
"columns": [
null,
null
]
});
// iterate all cell data as a JavaScript array of arrays:
var allData = table.data();
for (var i = 0; i < allData.length; i++) {
var rowData = allData[i];
for (var j = 0; j < rowData.length; j++) {
//console.log("row " + (i+1) + " col " + (j+1) + ": " + rowData[j]);
}
}
// get only one cell - row 3 column 2:
var oneSelectedCell = table.cell(2, 1);
//console.log(oneSelectedCell.data());
// get one cell's <td> node - row 3 column 2:
var oneSelectedCell = table.cell(2, 1);
//console.log(oneSelectedCell.node());
// get some cells using a css class name:
var someSelectedCells = table.cells(".foo").data();
for (var i = 0; i < someSelectedCells.length; i++) {
//console.log(someSelectedCells[i]);
}
// get only one cell without the HTML tags - row 3 column 2:
var oneSelectedCell = table.cell(2, 1);
var node = oneSelectedCell.node();
//console.log(node.textContent);
});
</script>
</body>
The final example shown above...
var oneSelectedCell = table.cell(2, 1);
var node = oneSelectedCell.node();
console.log(node.textContent);
...will print "foxtrot", with the enclosing <b> tag removed.
EDIT:
I forgot one useful function: every(). For example:
// get all nodes using the 'every()' function:
table.cells().every( function () {
console.log(this.node().textContent);
} );
This will list all the table cells' text values (removing embedded HTML, such as the <b> tag).
You can use string manipulation with this matter. You just need to get the indexes between the span tag. indexOf will get the first occurance of a string then use it to get the string you need with substring.
I added +1 on the first index because the start index return the position before the character so plus 1 will do the trick to make it after "<".
var str = "<span class='text-success font-weight-bold'>B81692097</span>";
var res = str.substring(str.indexOf(">")+1, str.indexOf("</"));
document.getElementById("result").innerHTML = res;
<p id="result"></p>
I want the user to input both 'part ID' and 'quantity' through prompt and have those values added to a table; which I've managed so far. After that, I want to add another row below the first one using the same method resulting in 2 rows with different values etc.
<html>
<head>
</head>
<!--CREATE AND POPULATE TABLE -->
<body onload="partID(); qty()">
<table id="resultsTable" border=".5px" class="results">
<tr><th>Part ID</th><th>Quantity</th>
<tr>
<td id="partID">Part ID</td>
<td id="qty">Quantity</td>
</tr>
</table>
<br>
<!-- I want this f('createTable') to bring the prompt back and append to existing table onclick, if that makes sense -->
<button onclick="createTable()">Add Another Part</button>
</body>
<!-- LOCAL SCRIPTS -->
<script>
function partID(){
var partID = prompt("Enter part ID:");
var x = document.getElementById('partID');
x.innerHTML = partID;
}
function qty(){
var qty = prompt("Enter Quantity:");
var y = document.getElementById('qty');
y.innerHTML = qty;
}
</script>
</html>
I can get it to work once around but I'm not sure how to repeat it for a new row and without losing previous data.
What you want to do is append data to the table, right now you are setting the values of individual cells instead of just appending them to the already existing ones.
JavaScript has a neat little shortcut for appending (just like many other languages) which is +=, basically var myVar = 'Foo'; myVar += 'Bar'; is equal to var myVar = 'Foo'; myVar = myVar + 'Bar';
function add() {
//prompt the user with boxes for the ID and quantity
var partID = prompt("Enter part ID:");
var qty = prompt("Enter Quantity:");
//generate the HTML for a new table row and insert the given values
var table_html = "<tr><td>" + partID + "</td><td>" + qty + "</td></tr>";
//append the HTML to the already existing HTML in the table
document.getElementById('resultsTable').innerHTML += table_html;
}
/*I dont like default buttons*/
button {
background-color: lightgrey;
color: black;
padding: 8px;
border: 0px;
}
button:hover {
background-color: grey;
}
<html>
<head>
</head>
<body onload="add();">
<!-- instead of onload use a button so the user can repeat the action multiple times -->
<button onclick="add();">Add part</button>
<hr>
<table id="resultsTable" border=".5px" class="results">
<tr>
<th>Part ID</th>
<th>Quantity</th>
</tr>
</table>
<br>
</body>
</html>
I hope this helps, if you need further explanation about the code just leave a comment.
Good luck.
From what I understand, you want to be able to add a new row to the <table>. For this, you probably want to use a button.
<button onclick="addRow()">Add row</button>
Then you can add a row using insertAdjacentHTML :
function addRow() {
var table = document.getElementById('resultsTable');
var partID = prompt("Enter part ID:");
var qty = prompt("Enter Quantity:");
table.insertAdjacentHTML('beforeend', "<tr><td>" + partID + "</td><td>" + qty + "</td></tr>")
}
Using insertAdjacentHTML is safer and more efficient than replacing the whole table innerHTML.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
For example I have the following text with no tags at all within the HTML page:
Color: red
Shape: square
Side: 1mm
As much rows as needed, but three is quite enough for this question. Even one would be.
In those rows I'll always have the beginning of the text string, colon+space (: ) and the end of the text string.
How should I turn the beginning of the text string into <tr><td>, colon+space into :</td><td> and the end of the text string into </td></tr>?
Thanks to #Andrew Willems (the script) and #Phil (further suggestions) everything is up and running.
The original text here has some extra unnecessary lines before and after the text to demonstrate the need for dealing with, and the ability to deal with, extra lines.
var opening = '<table id="newborn_table"><tbody>';
var closing = '</tbody></table>';
var origText = document.querySelector('#source').innerText;
var lines = origText.split('\n').filter(function(line) {
return (line !== "");
});
var rowsText = '';
lines.forEach(function(line) {
var parts = line.split(': ');
rowsText +=
'<tr><td>' +
parts[0] +
'</td><td>' +
parts[1] +
'</td></tr>'
});
document.querySelector('#result').innerHTML =
opening + rowsText + closing;
#newborn_table td {
border: solid red 1px;
}
<p>Original text:<p>
<pre id="source">
Color: red
Shape: square
Side: 1mm
</pre>
<p>Parsed table:</p>
<div id="result"></div>
Assuming you actually want something like...
<table id="newborn_table">
<tbody>
<tr>
<td>Color</td>
<td>red</td>
</tr>
<tr><!-- etc --></tr>
</tbody>
</table>
You should be able to map your string like so
function createTable(str, id) {
let table = document.createElement('table'),
tbody = document.createElement('tbody');
table.setAttribute('id', id || 'newborn_table');
table.setAttribute('border', 1);
table.appendChild(tbody);
str.split('\n').forEach(row => {
let tr = document.createElement('tr');
row.split(': ').forEach(cell => {
let td = document.createElement('td');
td.textContent = cell;
tr.appendChild(td);
});
tbody.appendChild(tr);
});
return table;
}
var str = `Color: red
Shape: square
Side: 1mm`;
document.body.appendChild(createTable(str));
I want to store some information in DOM elements (rows of table). I think I can do it using jQuery's data() function. I wrote some test code and found out that I can't get the stored data from elements using jQuery selectors. Is it possible? Maybe I'm doing something wrong?
Here is the simple code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JQuery data() test</title>
<script src="https://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
</head>
<body>
<table id="myTable">
<tbody>
<tr id="rowPrototype" style="display:none;">
<td class="td1"></td>
<td class="td2"></td>
</tr>
</tbody>
</table>
<script>
var table = $("#myTable");
for (var i = 0; i < 5; i++) {
var newRow = $("#rowPrototype").clone();
newRow.removeAttr("style");
newRow.removeAttr("id");
$.data(newRow, "number", i);
console.log("Data added to row: " + $.data(newRow, "number"));
var tds = newRow.find("td");
tds.text("test");
table.append(newRow);
}
var trs = table.find("tr");
trs.each(function () {
var tr = $(this).text();
var data = $.data(tr, "number");
console.log("number: " + data);
});
</script>
</body>
</html>
I expect the following output:
number: undefined (row prototype)
number: 0
number: 1
number: 2
number: 3
number: 4
But actual is:
number: undefined
number: undefined
number: undefined
number: undefined
number: undefined
number: undefined
So what's wrong with this code?
UPD
You can test it here: https://jsfiddle.net/rfrz332o/3/
$.data() expects an actual DOM element as the first argument, not a jQuery object. You can $(selector).data() with jQuery objects. I'd suggest you change this:
$.data(newRow, "number", i);
console.log("Data added to row: " + $.data(newRow, "number"));
to this:
newRow.data("number", i);
console.log("Data added to row: " + newRow.data("number"));
And, then change this:
var trs = table.find("tr");
trs.each(function () {
var tr = $(this).text();
var data = $.data(tr, "number");
console.log("number: " + data);
});
to this:
table.find("tr").each(function () {
console.log("number: " + $(this).data("number"));
});
You messed with data method. You weren't applying data to dynamic created row. To see result, please check your console.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JQuery data() test</title>
<script src="https://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
</head>
<body>
<table id="myTable">
<tbody>
<tr id="rowPrototype" style="display:none;">
<td class="td1"></td>
<td class="td2"></td>
</tr>
</tbody>
</table>
<script>
var table = $("#myTable");
for (var i = 0; i < 5; i++) {
var newRow = $("#rowPrototype").clone();
newRow.removeAttr("style");
newRow.removeAttr("id");
newRow.data("number", i);
console.log("Data added to row: " + newRow.data("number"));
var tds = newRow.find("td");
tds.text("test");
table.append(newRow);
}
var trs = table.find("tr");
trs.each(function () {
var tr = $(this).text();
var data = $(this).data("number")
console.log("number: " + data);
});
</script>
</body>
</html>
$.data() expects DOM element, not jQuery object. Add [i] or use .get(i) at $.data(newRow[i], "number", i); and all js that follows where $.data() is used to reference DOM element.
There is also an issue with the for loop. If there is actually only one tr element and two td elements within #myTable, when i reaches 2 , if the selector included i the result would be undefined, as the maximum index of td elements would still be 1 within the cloned table ; whether $.data() or .data() is used. Similarly for the one tr element within #myTable; when i reaches 1
jQuery.data( element, key, value )
element
Type: Element
The DOM element to associate with the data.
Hi I have 3 questions, if you have for example this simple website
<html> <head> </head> <body> <table>
<tr> <td>www.hello1.com</td>
</tr> <tr> <td>www.hello2.com</td>
</tr> </table> </html>
Question 1)
If I for instance decide to click on link number 2 (www.hello2.com), Is this stored in some kind of variable?
I know that this is storing the current URL but not the one that you click
window.location.href;
Question 2)
How do you search your document, say that I would like to search the this website and store all the links in a javascript array like this
var myArray = [];
searchThisWebSiteForURLS()//Do this function that I don't know to write that search this htmlsite for url's
var myArray = [ 'http://www.hello1.com', 'http://www.hello2.com'];//This is the reslt after that the function has been executed
Question 3)
I would like to write out these links. Say that I have another table like this
<html> <head> </head> <body> <table>
<tr> <td>X</td>
</tr> <tr> <td>Y</td>
</tr> </table> </html>
Where X = http://www.hello1.com
And Y = http://www.hello2.com
Of course it shall be as many rows as there are elements in the array like this
<html> <head> </head> <body> <table>
<tr> <td>X</td></tr>
<tr> <td>Y</td></tr>
<tr> <td>Z</td></tr>
<tr> <td>A</td></tr>
<tr> <td>B</td></tr>
</table> </html>
Where Z, A, B are the elements 3,4,5 in the array
var myArray = [ 'http://www.hello1.com', 'http://www.hello2.com','http://www.hello3.com','http://www.hello4.com','http://www.hello5.com'];
EDIT!--------------------------------------------------------------------------
Wow really thanks, all of you, really thanks! I just have one more question regarding the links, when comparing two links, say that the array looks like this
var pageLinks = ['http://www.example.at', 'http://www.example2.at', 'http://www.someothersite.at'];
And say that the user has pressed the example "http://www.example.at" link, then I want to create the table containing the similar links. So I do something like this
function checkForSimilarLink(theLinkToCompareWith){// in this case theLinkToCompareWith = "http://www.example.at"
var numLinks = pageLinks.length;
for(var i = 0; i < numLinks; i++) {
//Check if numLinks[i]== theLinkToCompareWith*
}
}
So how would you write this compare function? In this case we can consider
"http://www.example.at" and "http://www.example1.at" the "same" while "http://www.someothersite.at" obviosly aren't
Thanks again :)
I didn't understand question 1, but here's something for question 2 and 3:
Question 2:
var pageLinks = [];
var anchors = document.getElementsByTagName('a');
var numAnchors = anchors.length;
for(var i = 0; i < numAnchors; i++) {
pageLinks.push(anchors[i].href);
}
//now pageLinks holds all your URLs
Question 3:
// say pageLinks holds your desired URLs
var pageLinks = ['http://www.example.at', 'http://www.example2.at', 'http://www.example3.at'];
// create an empty table
var table = document.createElement('table');
// ... and it's tbody
var tbody = document.createElement('tbody');
// loop through your URLs
var numLinks = pageLinks.length;
for(var i = 0; i < numLinks; i++) {
// create new table row...
var tr = document.createElement('tr');
// a cell...
var td = document.createElement('td');
// and your anchor...
var a = document.createElement('a');
// set the anchor's href
a.setAttribute('href', pageLinks[i]);
// set the anchor's text, it's also the URL in this example
a.innerHTML = pageLinks[i];
// append the anchor to the table cell
td.appendChild(a);
// ... and that cell to the new row
tr.appendChild(td);
// ... and that row to the tbody, right? ;-)
tbody.appendChild(tr);
}
// after all rows were added to the tbody,
// append tbody to the table
table.appendChild(tbody);
// and finally append this table to any existing
// element in your document, e.g. the body:
document.body.appendChild(table);
// ...or add it to a div for example:
//document.getElementById('anyDiv').appendChild(table);
Go study JQuery!!!! XDD The best for web development.
for the first and second question in with jquery:
var anchors = $('a'); //returns all <a></a> elements from here you can get the url from all of theam
With jquery u can write any element that you want.
var table = $('<table></table>');
var tr = $('<tr></tr>').appendTo(table);
var td = $('<td></td>').setText('your link here')appendTo(tr);
. . .
table.appendTo(The parent element to add the table);
Question 1:
You can capture the onclick event for clicking on the link and during that store whatever information you want to a variable of your choosing (though, this would only be relevant if you included return false in the onclick event because the link would otherwise take the user to a new page and end your session).
Question 2 and 3 were answered quite well by Alex.