jQuery push text from inside / outside of brackets to array - javascript

I use json save for a template builder. And I convert some blocks and html tables into simple tags, eg: [[TableName(Title,SKU,Total)]]
The code for this tag looks like this:
<div class="box table">
<table id="TableName">
<thead>
<tr>
<td class="title">Title</td>
<td class="sku">SKU</td>
<td class="total">Total</td>
</tr>
</thead>
<tbody>
<tr>
<td class="title"></td>
<td class="sku"></td>
<td class="total"></td>
</tr>
</tbody>
</table>
</div>
On load, I need to convert tag back to html, so I use:
var tag = []
template.find('.table').each(function(){
var array = $(this).html().match(/\(([^)]+)\)/)[1].split(',');
tag.push(array);
});
console.log(tag)
but I need to get the id too "TableName" than generate the table.

Maybe you need simpler templating engine :
You can try handlebarjs. It's very easy to use and have good performance.
http://handlebarsjs.com/
https://www.youtube.com/watch?v=4HuAnM6b2d8

var $tableID = $(".table").attr("id"); // gets the table's id
var tag = []
template.find('.table').each(function(){
var array = $(this).html().match(/\(([^)]+)\)/)[1].split(',');
tag.push(array);
});
console.log(tag)

Related

Validation of HTML table generated by WYSIWYG editor in Javascript

I have a form with several input fields including WYSIWYG editor as an input field. In WYSIWYG editor user enter data using HTML table. But sometime happen while adding new row user enter new table snippet within in the same row as in the below code.
<table width="100%">
<tbody>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td>
<table width="100%">
<tbody>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
How can I validate this HTML code snippet using Javascript? How can I identify that within or in table tag (<table) exist. Any help would be appreciated.
You can create an element out of your HTML like this:
function htmlToElement(html) {
var template = document.createElement('template');
html = html.trim(); // Never return a text node of whitespace as the result
template.innerHTML = html;
return template.content.firstChild;
}
const myTable = htmlToElement('<table width="100%">....</table>');
... and then check if there is a table within the table:
if (myTable.querySelector('table')) {
// ...
}
Credits for the htmlToElement function: Creating a new DOM element from an HTML string using built-in DOM methods or Prototype

How do I filter a table by any matching code/name and not every available field

I'm trying to do the following: I have a table populated with data from the DB. Apart from that, I have an input where you can write something and a button that will filter, only showing the lines that have that string. This is working now!
The thing is, the input should only allow you to filter by foo.name/foo.code (two propertys of my entity).
I'm adding the code I have in case anyone can guide me out, I've tried several things but this are my first experiences with JQuery while I have a strict story-delivery time. Thanks everyone!
<tbody>
<c:forEach var="foo" items="${foo}">
<tr id = "fooInformation" class="mtrow">
<th id="fooName" scope="row">${foo.name}</th>
<td id="fooCode" class="left-align-text">${foo.code}</td>
<td class="left-align-text">${foo.country}</td>
<td class="left-align-text">${foo.region}</td>
<td class="left-align-text">${foo.subregion}</td>
</tr>
</c:forEach>
</tbody>
$("#search").click(function () { -> button id
var value = $("#fooRegionSearch").val(); -> value of the input
var rows = $("#fooRegionTable").find("tr"); -> table id
rows.hide();
rows.filter(":contains('" + value + "')").show();
});
To start with, your HTML is invalid - there cannot be elemenets with duplicate IDs in HTML. Use classes instead of IDs.
Then, you need to identify which TRs pass the test. .filter can accept a callback, so pass it a function which, given a TR, selects its fooName and fooCode children which contain the value using the :contains jQuery selector:
$("#search").click(function() {
var value = $("#fooRegionSearch").val();
var rows = $("#fooRegionTable").find("tr");
rows.hide();
rows.filter(
(_, row) => $(row).find('.fooName, .fooCode').filter(`:contains('${value}')`).length
).show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="fooRegionTable">
<tr id="fooInformation" class="mtrow">
<th class="fooName" scope="row">name1</th>
<td class="fooCode" class="left-align-text">code1</td>
<td class="left-align-text">${foo.country}</td>
<td class="left-align-text">${foo.region}</td>
<td class="left-align-text">${foo.subregion}</td>
</tr>
<tr id="fooInformation" class="mtrow">
<th class="fooName" scope="row">name2</th>
<td class="fooCode" class="left-align-text">code2</td>
<td class="left-align-text">${foo.country}</td>
<td class="left-align-text">${foo.region}</td>
<td class="left-align-text">${foo.subregion}</td>
</tr>
</table>
<button id="search">click</button><input id="fooRegionSearch" />

Selecting content with JQuery

Any ideas why this doesn't work?
http://jsfiddle.net/zk4pc/2/
I'm trying to get it so that everytime there is an element with the class "insert_name", the name is printed from the table.
Could you also help me make the selection more advanced (for instance only using the data from the first tr in the "client-profile" class?
Thanks!
HTML
<body onload="printMsg()">
<div id="api_data" style="display:none;">
<div class="client-profile">
<div class="head icon-5">Customer Details</div>
<table id="client-information">
<tbody>
<tr>
<td class="left">Name:</td>
<td class="color">Matthew Tester
</td>
</tr>
<tr class="dark">
<td class="left">E-mail:</td>
<td class="color">asdfg</td>
</tr>
<tr>
<td class="left">Registration:</td>
<td class="color">2013-11-21</td>
</tr>
<tr class="dark">
<td class="left">Status:</td>
<td class="color"><span class="active">Active</span>
</td>
</tr>
<tr>
<td class="left">Last Login Time:</td>
<td class="color" title="2014-05-28 11:43:46">1 hour ago</td>
</tr>
<tr class="dark">
<td class="left">Last Login From:</td>
<td class="color">123.123.123.123</td>
</tr>
<tr>
<td class="left">Location:</td>
<td class="color">United Kingdom</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="insert_name"></div>
</body>
Javascript
(function printMsg() {
var node = document.getElementsByClassName('insert_name');
node.innerHTML = $('[class*="color"]').eq(0).text();
})();
jsFiddle Demo
The issue is with your node selection. When you select by class name it returns an array of elements. Since you are only looking for the div with that class name, access the first index to reference it.
var node = document.getElementsByClassName('insert_name')[0];
edit
To make this iterate all of the nodes you could take this approach
var nodes = document.getElementsByClassName('insert_name');
var text = $('[class*="color"]').eq(0).text();
for(var i = 0; i < nodes.length; i++){
nodes[i].innerHTML = text;
}
Alternatively, since jQuery is already included, you could remove the body's onload event and just use this
jsFiddle Demo
$(function(){
$('.insert_name').html($('[class*="color"]').eq(0).text());
});
To ensure this only acts on the client-profile class the selector would be
$('.insert_name').html($('.client-profile [class*="color"]').eq(0).text());
If you are just trying to insert the name rather than all of the content, this should do the trick:
$(function() {
$('.insert_name').text($('td:contains("Name:")').next().text());
});
Here is the fiddle:
http://jsfiddle.net/b8LKQ/
Hope that helps!
I added a little more jQuery:
$(function() {
$('[class*="color"]').each(function(){
$('.insert_name').append($(this).text());
});
});
http://jsfiddle.net/zk4pc/7/
Hope that helps!

Using multiple values in a filter function jquery data attribute example

I was looking at the usage of jquery filter for data attributes, in this case, tables containing three data variables, i.e, team, specialization and level. Please do let me know what the best approach is and what the typical usage methodology are.
Here is my code html:
<table data-team="<?php print $name['team']; ?>" data-specialization="<?php print $name['speciality']; ?>" data-level="<?php print $name['level']; ?>" cellpadding="0" cellspacing="0" border="0" width="670px" class="jobs"><tr><td>
<tr><td colspan="4"><strong><?php print $name['title'] ?></strong></td>
<td></td><td></td><td></td></tr>
<tr>
<td width="100">Location : </td>
<td colspan="3"><?php print ($name['location']);?> </td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td> Job Code : </td>
<td width="460"><?php print $name['id'] ?></td>
<td></td>
<td></td>
<td><a data-action="showDesc,jumpTo" href="javascript:;" id="<?php print($name['id']);?>" class="more">More Details </a></td>
</tr></td></tr>
</table>
The javascript that I have I got from one other Stack Overflow question, and it works on showing based on one matching attribute, here is my code:
$("#search").click(function() {
var team=$('#selectOne').val();
var specialty=$('#selectTwo').val();
var level=$('#selectThree').val();
var teams=[];//
var special=[];
var level=[];
//teams=$('.jobs').data('team');
//alert(teams);
$(".jobs").hide();
$('.jobs').filter(function(){
return $(this).data('team') === team;
}).show();
});
});
I want to put all the data-team attributes into the array, iterate over it and then check if each table contains it, in which case to the next array, to check and so on. if the data values match then, show.
Turns out my error was just that I re-declared the variables team[]. so basically, this:
$('.jobs') .hide().filter('[data-team="'+team+'"][data-specialization="'+specialty+'"][data-level="'+level+'"]').addClass('num').show();
Works fine now.

Remove tables from HTML using jQuery

I've got many chunks of HTML coming into my app which I have no control over. They contain tables for layout, which I want to get rid of. They can be complex and nested.
What I want is to basically extract the HTML content from the tables, so that I can inject that into other templates in the app.
I can use jQuery or plain JS only, no server side trickery.
Does anyone know of a jQuery plugin of good tip that will do the job?
Littm - I mean to extract content from the td tags essentially. I want no trace of table left in the code when it's done. Thanks!
Here's an example of the type of HTML in question. It all comes in via XHR from some ancient application so I have no control over the markup. What I want is to get rid of the tables completely, leaving just the rest of the HTML or other text content.
<table>
<tr><td colspan="4"></td></tr>
<tr>
<td width="1%"></td>
<td width="40%" style="padding-left: 15px">
<p>Your access level: <span>Total</span></p>
</td>
<td width="5%">
<table><tr><td><b>Please note</b></td></tr></table>
</td>
<td width="45%" style="padding-left: 6px" valign="top"><p>your account</p></td>
</tr>
<tr><td colspan="4"> </td></tr>
<tr>
<td width="1%"></td>
<td width="40%" style="padding-left: 15px">
<table>
<tr>
<td align="right">Sort Code: </td>
<td align="center"><strong>22-98-21</strong></td>
</tr>
<tr>
<td align="right">Account Number: </td>
<td><strong>1234959</strong></td>
</tr>
</table>
</td>
<td width="5%"></td>
<td width="45%" style="padding-left: 6px">Your account details for</td>
</tr>
</table>
I've tried;
var data = ""
$("td").each(function(){
data += $(this).html()
});
$("article").append(data);
$("table").remove();
But var data still contains nested td tags. I'm no JS expert so I'm not sure what else to try....
Let's suppose that you have X number of tables.
In order to extract all the content information from these, you could try something like this:
// Array containing all the tables' contents
var content = [];
// For each table...
$("table").each(function() {
// Variable for a table
var tb = [];
$(this).find('tr').each(function() {
// Variable for a row
var tr = [];
$(this).find('td').each(function() {
// We push <td> 's content
tr.push($(this).html());
});
// We push the row's content
tb.push(tr);
});
// We push the table's content
content.push(tb);
});
So for instance, if we have the following 2 tables:
<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>A</td>
</tr>
</table>
<table>
<tr>
<td>r1</td>
<td>r2</td>
<td>r3</td>
</tr>
<tr>
<td>rA</td>
<td>rB</td>
</tr>
<tr>
<td>rP</td>
</tr>
</table>
The array content will be something like this:
content = [ [ [1, 2], [A] ] ] , [ [r1, r2, r3], [rA, rB], [rP] ] ]
\_______________/ \______________________________/
1st table 2nd table
and if you want to access the first table, you'll just have to access content[0] for instance.
Now, let's suppose that you have a DIV, with and id my_div, and that you want to output some table content in it.
For example, let's suppose that you only want to have the 1st table only. Then, you would do something like this:
// Note: content[0] = [[1, 2], [A]]
var to_print = "<table>";
for(var i=0; i<content[0].length; i++) {
to_print += "<tr>";
for(var j=0; j<content[0][i].length; j++)
to_print += "<td>"+ content[0][i][j] +"</td>";
to_print += "</tr>";
}
to_print += "</table>";
$("#my_div").html(to_print);
which will give you something like this:
<div id="my_div">
<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>A</td>
</tr>
</table>
</div>
Hope this helps.
Edit: You should create a recursive function to do that.
Simply create you function that gets "td"'s as a value:
function searchTexts(td) {
if (td.find("td")) {
searchTexts(td.find("td"));
}
td.each(function(){
data += $(this).html()
$(this).remove(); // remove it for avoiding duplicates
});
}
Then call it passing a jQuery object to the function.

Categories

Resources