jQuery DataTables: Avoid linebreaks in cells - javascript

I don't have a CSS problem, but a logical problem. I want to get rid of automatic linebreaks in my table cells. For some reason, long pieces of data are split in two lines, even in the HTML itself. This means that none of the classic CSS attributes are going to help here.
Example:
<td class="sorting_1">SAP-IT Projekt
Welle 1</td>
The value inside of the td element is cut in two.
What I've tried:
{
"data": "Project.Name",
"editField": "ProjectEntry.IdProject",
"render": function (project) {
// This code doesn't really work, the cells still contain linebreaks.
project = project.trim().replace(/(\r\n\t|\n|\r\t)/gm, "");
console.log(project);
return project;
}
}
Note: The logging in this render function outputs the string without linebreaks.
I think I'm missing a crucial piece of configuration that prevents these automatic linebreaks.
The table used to have the "responsive" piece of configuration, but I've removed that.
Update:
Here's the style of each cell:
#ProjectEntryDataContainer, #ProjectEntryDataContainer > div > table > tbody > tr > td {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
table-layout: fixed;
}
This style is being applied to each cell, according to Chrome's DevTools. The table element hast the class nowrap.
As I've mentioned, the CSS has little to nothing to do with my issue. The text is being displayed in one line, but the HTML element has a line break in it. I want to get rid of the line break in my HTML so I can search the cells properly, using jQuery code. I'm currently using the following code to search my cells:
var project = rowData.Project.Name.trim().replace(/(\r\n\t|\n|\r\t)/gm, "");
// Find our required cell that we want to edit. If we can't find one, create a new one.
var colHeaderTarget = $("#ProjectEntryData").find('th:contains("Arbeitsstunden")')[0];
var rowHeaderTarget = $("#ProjectEntryData").find('td:contains("' + project + '")')[0];
var projectRows = $("#ProjectEntryData").find("tr:contains('" + project + "')");
console.log(project);
console.log(projectRows);
This code works wonderfully as long as the cell doesn't have linebreaks.
I just found out that my JSON data contains linebreaks. I'll update once I find out more.
{IdProject: 35, Name: "SAP-IT Projekt
↵ Welle 1", Description: null,
Update: The SQL data contained linebreaks... See answer.

Turns out that when your database contains line breaks you're going to get line breaks in the HTML. If anyone has a solution that causes DataTables to filter out line breaks in the cell data, I'll mark that one as the accepted answer. Otherwise, I'll just advise everyone to avoid linebreaks in your SQL data.

try it worked for me very well.

Related

I'm trying to set a generic element invisible by attribute and in one line of javascript

I'm limited to one line because of a Chrome Extension and it's the only one that fits my needs.
The <td> needs to be gone through to the attribute "UserName" to determine if a blocked user needs to be invisible.
I cannot figure this out and I'm really a noob when it comes to Javascript (not my language)
I've tried display:none hidden and style.visibility="hidden".
I've tried w3Schools and searched through Javascript and HTML pages for how to this and while I've got code that does work, it's a script that takes about 8 lines which doesn't work. I may have to ditch it but I figured I've give it one last shot.
document.getElementsByTagName("td")[0].getAttribute("theUserName").value("madmax").style.visible = "hidden";
Expected - The <td> should not show up
Results - It shows up
One line to hide the content:
[...document.querySelectorAll("td[theUserName=madmax]")].forEach(e=>e.style.display = 'none');
To remove the <td>:
[...document.querySelectorAll("td[theUserName=madmax]")].forEach(e=>e.remove());
I am assuming that you to iterate through all <td> elements to search for one with theUserName attribute with value madmax, then make that element invisible. That can be achieved with:
for(TdElement of document.getElementsByTagName("td")) {
if (TdElement.getAttribute("theUserName") == "madmax") {
TdElement.style.visiblity = "hidden";
}
}
Condensed to a single line, this is:
for(TdElement of document.getElementsByTagName("td")) if TdElement.getAttribute("theUserName") == "madmax") TdElement.style.visiblity = "hidden"

Get rendered html as text, including newlines

I have a page with some html rendered into it.
I want to get the rendered page as text, but somehow also include the newlines. In addition, if relevant, I'm looking for an extended solution that will also support lists (using spaces and •), tables (using spaces, but with no borders) and similar cases.
I'm looking for Javascript solution, either on client or server side.
Please mind: not every element in the page equals to new line (e.g: some divs can be inline and some can create new lines).
For exapmle, this snippet below will be the html, and the output will be the text itself as you can see below (after running).
#inline{
display:flex;
flex-direction:row;
}
#inline div{
margin-right:5px;
}
#notInline{
display:flex;
flex-direction:column;
}
<div>
<div id='inline'><div>some</div><div>divs</div><div>inline</div></div>
<div id='notInline'><div>some</div><div>divs</div><div>on top of each other</div>
You can try this. First inline text second "on top of each other" text:
var inlineOutput = '';
document.querySelector('#inline').childNodes.forEach(e=>{inlineOutput += e.textContent + ' '}) + "\n";
console.log(inlineOutput);
var noInLineOutput = '';
document.querySelector('#notInline').childNodes.forEach(e=>{noInLineOutput += e.textContent + " \n"});
console.log(noInLineOutput);
There's a js scraper called Cheerio that could extract all the text out for you, I've never used it though. It gives you access to the DOM and you can gather parts of whichever page you need. here's a tutorial that uses it with node.
Not sure if this is what you're looking for, if they're your own pages you can probably make a function that calls everything in the dom and delimits at the open close carats and grabs in the text inbetween, and maybe make a switch if it sees the notInLine class

Add code examples on your page with Javascript

I have a html code inside string
string_eng += '<b>Year Bonus</b> - bonus for each year</br></br>';
And I want to put this inside textarea, but when I do it, the result is:
- bonus for each year
It simply deletes all things inside the html tags. I just want to show all the code inside the string. I already tried <xmp>,<pre>, but none of them worked.
Thanks for any help.
EDIT.
Code with which I input data from the array to the textarea/code.
$('body').append('<code class="code_text"></code>');
for(var i=0; i<tag_list.length; i++){
var string='';
string+='---------------------------------------------------------------------------------\n';
string+='tag: '+tag_list[i][0]+'\n';
string+='nazwa_pl '+tag_list[i][1]+'\n';
string+='nazwa_eng '+tag_list[i][2]+'\n';
string+='tekst_pl '+tag_list[i][3]+'\n';
string+='tekst_eng '+tag_list[i][4]+'\n';
string+='\n\n\n';
$('.code_text').append(string);
}
I tried this using jsfiddle:
HTML
<textarea id="code"></textarea>
JavaScript
$(document).ready(function() {
var string_eng = '';
string_eng += '<b>Year Bonus</b> - bonus for each year</br></br>';
$("#code").html(string_eng);
});
Output (contained in textarea)
<b>Year Bonus</b> - bonus for each year</br></br>
Try it here: http://jsfiddle.net/UH53y/
It does not omit values held within tags, however if you were expecting the <b></b> tags to render as bold within the textarea, or the <br /> tags to render as line breaks, this wont happen either. textarea does not support formatting.
See this question for more information: HTML : How to retain formatting in textarea?
It's because you're using the jQuery .append method which seems to parse the string and insert it afterwards. I don't know jQuery at all, so there might be another special jQuery method, but here is a simple fix:
$('.code_text').append(document.createTextNode(string));
Edit:
I just read and tried the answer of Salman A. The "special jQuery method" exists and he used it. You can use this:
$('.code_text').text(string);

jquery or javascript: Truncate text in table cell

I need to truncate the text in the first column of a table using javascript or jQuery. Here's where I'm at:
The table:
<table id="bigTable">
<tr><td>Text is tooooo looong</td><td>Just Right</td></tr>
<tr><td>Text is tooooo looong</td><td>Just Right</td></tr>
<tr><td>Text is tooooo looong</td><td>Just Right</td></tr>
</table>
Trying stuff like the following without success ( compiled from other similar posts ):
var lbl = $("#bigTable tbody");
var newLbl = $(lbl[0].outerHTML);
$('td:eq(0)', newLbl).slice(5);
It does not seem to be getting the contents, or text from the cells. Has no effect whatsoever. Tried also -
$('td:eq(0)', newLbl)contents().slice(5);
$('td:eq(0)', newLbl).text().slice(5);
What am I doing wrong?
EDIT
Before more down-voting and general grumpy-ness occurs ...
I have to have the text from a div copied to a variable for manipulation and later display in a different window/div.
This happens in response to a button click.
...but applying the css rules sounds promising. Will try that instead.
Please see this fiddle to understand what I need to do:
http://jsfiddle.net/Vsse3/2/
I have to be able to wrap column cells with a div before using the css idea.
You don't need js, using CSS:
demo:
http://jsfiddle.net/vTDAQ/3/
#elckarns comment is correct but you also need to wrap the cell content in a div to use text-overflow.
Also note that your table is not well formed.
demo updated as requested:
http://jsfiddle.net/Vsse3/6/

jQuery break out of table

I have a standard HTML formatted table, that dynamically generates the content, via Zend Framework. From which I have an issue altering the form internally PHP side. So I need to alter the tables appearance somehow. With that on the occasion I have an element show up in one of the rows and when this element shows up I want to break out of the table and then do something after it then start the table again.
Basically I want to inject the equivlant of
</tbody></table>/*other stuff*/<table><tbody> after the row containing the one element I seek which in this case is a label.
I tried $("label[for='theLable']").parents('tr').after('</tbody></table><br><table><tbody>') which appears to ignore the ending table parts add the br, and then does a complete open/close tag for table and tbody within the same table I am trying to break out of so inbetween tr tags basically it adds this new table
Whats the best way to approach this concept?
update with jsfiddle link
http://jsfiddle.net/cPWDh/
You can't really modify the HTML of the document the way you're thinking, since it's not a legitimate way to alter the DOM.
Instead, I would create a new table and .append the rows you want to move to it, which will automatically move them from their current location (instead of copying them):
$(document).ready(function() {
var $trow = $('label[for="specialLabel"]').closest('tr'),
$table = $trow.closest('table');
$('<table>').append( $trow.nextAll().andSelf() ).insertAfter($table);
});​
http://jsfiddle.net/cPWDh/1/
this approach won't work in js. What you could do if the table has not too many rows is this:
var nextTable = $("table").after("/*other stuff*/<table id="nextTable"></table>");
//now you loop over the lines of your original table that you want to have after the "break", and move them to the nextTable:
var before = true;
$("table tr").each(function(){
if ($(this).has("[for='theLable']")) {
before = false;
}
if (!before) {
nextTable.append($(this));
}
});

Categories

Resources