jQuery select all emails from text area - javascript

I am trying to select dynamically all valid emails which are entered into a text area and spaced by either a space or a comma. (I'm not sure how to use a regex to achieve this in javascript).
My main issue is a number of false positives and extra duplicate information is being displayed, (I assume from using keyup), is there a way to fix this problem so it only shows each valid email once?
$(document).ready(function(){
$('.emails').keyup(function () {
var matches = $('.emails').val().split(' ');
for (var i = 0; i < matches.length; i++){
if (validEmail(matches[i])){
$('#emails-send').append("<div class='newmail'>" + matches[i] + "</div>");
}
}
});
function validEmail(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
});

You could store the results in another object and check if they're already appended like this: http://jsfiddle.net/LKPwg/2/
this also uses a timeout to prevent incomplete emails addresses to be added.
var results = {};
var timer = null;
$(document).ready(function() {
$('.emails').keyup(function() {
clearTimeout(timer);
timer = setTimeout("parseEmails()", 500);
});
});
function parseEmails() {
var matches = $('.emails').val().split(' ');
for (var i = 0; i < matches.length; i++) {
if (validEmail(matches[i])) {
if (results[matches[i]] == undefined) {
results[matches[i]] = matches[i];
$('#emails-send').append("<div class='newmail'>" + matches[i] + "</div>");
}
}
}
}
function validEmail(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};​
as for the comma/whitespace seperation, you could replace comma with whitespace first:
$('.emails').val().replace(',', ' ').split(' ')
UPDATE
http://jsfiddle.net/LKPwg/4/
alternate way of checking for duplicates, by searching for a substring of the found token in the results and just updating the result-div in that case:
(this example doesn't need the timeout and uses the data-attribute to identify results)
var substr = matches[i].substr(0, (matches[i].length - 1));
if (results[substr]) {
delete results[substr];
$('#emails-send .newmail[data-email="' + substr + '"]').html(matches[i]).attr('data-email', matches[i]);
}
else {
$('#emails-send').append("<div class='newmail' data-email=" + matches[i] + ">" + matches[i] + "</div>");
}

Related

Javascript Substring replace with JQuerys contains selector

I'm trying to find a specific row in a column of an HTML table and replace an occurrence of a specific string with a given value.
I tried to use JQuery's .html but it just replaces everything in the row with the given value. A .text().replace() returned me false.
Here's my code:
function ReplaceCellContent(find, replace)
{
//$(".export tr td:nth-child(4):contains('" + find + "')").html(function (index, oldHtml) {
// return oldHtml.replace(find, replace);
//});
$(".export tr td:nth-child(4):contains('" + find + "')").text($(this).text().replace(find, replace));
//$(".export tr td:nth-child(4):contains('" + find + "')").html(replace);
}
$('.export tr td:nth-child(4)').each(function () {
var field = $(this).text();
var splitter = field.split(':');
if (splitter[2] === undefined) {
return true;
} else {
var splitter2 = splitter[2].split(',');
}
if (splitter2[0] === undefined) {
return true;
} else {
$.post(appPath + 'api/list/', {action: 'getPW', pw: splitter2[0]})
.done(function (result) {
ReplaceCellContent(splitter2[0], result);
});
}
});
I'm iterating through every row of the column 4 and extracting the right string. This is going through an AJAX post call to my function which returns the new string which I want to replace it with.
splitter2[0] // old value
result // new value
I hope someone could help me. I'm not that deep into JS/JQuery.
findSmith findJill findJohn
var classes = document.getElementsByClassName("classes");
var replaceCellContent = (find, replace) => {
for (var i = 0; i < classes.length; i++) {
if (classes[i].innerText.includes(find)) {
classes[i].innerText = classes[i].innerText.replace(find, replace);
}
}
}
this replaces all "fill" occurrences to "look".
I love to use vanilla JS, I'm not really a fan of JQuery but this surely should work on your code.
Do like this :
var tds = $("td");
for( var i = 0; i < tds.length ; i++){
if ( $(tds[i]).text().includes("abc") ){
var replacetext = $(tds[i]).text().replace("abc", "test");
$(tds[i]).text(replacetext);
}
}
Say give all your table rows a class name of "trClasses"
var rows = document.getElementsByClassName("trClasses");
for (var I = 0; I < rows.length; I++) {
rows.innerText.replace("yourText");
}
The innerText property would return the text in your HTML tag.
I'm a newbie too, but this should work. Happy Coding!

Locate Existing Numbers For Hyperlink In Textarea Set Next Avaibale One On Save / Click Modal

I am using CodeIgniter & jQuery and parsedown/markdown When I open my bootstrap modal, it allows me to create a new Reference-style link like on here.
I am trying to be able to find some how where it can find the next free number for my available in my textarea and when click save in model will set it.
I am fine [exmple-1][1] and [example-3][3]
[1]: http://www.example.com
[3]: http://www.example.com
And when I open my bootstrap modal and create a new hyperlink it will set and add the next available number
Here is the Codepen Example
Question: How can I when I create a new hyperlink in my bootstrap modal
and click save it can find the next available number set it. Because only 1 & 3 are set in example above next one should be 2 when click save in model
currently as you can see below I just use var counter = 1; and counter++; to be able to create numbers.
Script:
$('#myLink').on('shown.bs.modal', function() {
var text = getSelectedText();
$('#title').val(text.trim());
$('#url').val('http://');
});
function getSelectedText() {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var sel = textarea.value.substring(start, end);
return sel;
}
var counter = 1;
$('#save-link').on('click', function(e) {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var sel = textarea.value.substring(start, end);
var replace = '[' + $('input#title').val() + ']' + '[' + counter + ']';
var id = '\n [' + counter + ']: ' + $('input#url').val();
counter++;
if ($('#title').val().length > 0) {
textarea.value = textarea.value.substring(0,start) + replace +
textarea.value.substring(end,len) + ' \n' + id;
$('#myLink').modal('hide');
//$('#myLink form')[0].reset();
} else {
return false;
}
});
You can use a simple regex to find the used numbers in the textarea:
function findAvailableNumber(textarea){
//Find lines with links
var matches = textarea.value.match(/(^|\n)\s*\[\d+\]:/g);
//Find corresponding numbers
var usedNumbers = matches.map(function(match){
return parseInt(match.match(/\d+/)[0]); }
);
//Find first unused number
var number = 1;
while(true){
if(usedNumbers.indexOf(number) === -1){
//Found unused number
return number;
}
number++;
}
return number;
}
Add the function, remove the line var counter = 1; and replace counter++; with var counter = findAvailableNumber(textarea);
JSFiddle
As Barmar said: store your already generated numbers in an object or an array and check for the next non-existing number:
var existingNumbers = [1, 3];
function getNextNumber() {
var i = 1;
while (existingNumbers.indexOf(i) > - 1) {
i++;
}
existingNumbers.push(i);
return i;
}
Then get the next number with:
var number = getNextNumber();

Using separators in JS

I'm currently writing a program that uses ";" as a seperator and extracts the url up until that point upon searching the content.
So it has the format:
name;surname
In searching the given arrays... I decided to go the extra mile and test for arrays without the ";" but this has confused the program - it has no idea of the ";" position anymore and this throws a spanner in the works!
Here is my code so far - many thanks in advance!
pages =
[
"The first", "An;alternative;page", "Yet another page"
]
u_c_pages =
[
"www.cam.ac.uk;"+pages[0]
,
"www.warwick.ac.uk"+pages[1]
,
"www.kcl.ac.uk;"+pages[1]
,
"www;"+pages[2]
]
var pattern5 = prompt('5) Please enter a search term:');
function url1_m1(u_c_pages,pattern)
{
var seperator = [];
var seperatorPos = [];
if(pattern)
{
for (var i = 0; i < u_c_pages.length; i++)
{
var found = true;
if((u_c_pages[i].indexOf(";"))<0)
{
found=false;
}
else
{
seperator[seperator.length] = i;
seperatorPos[seperatorPos.length] = (u_c_pages[i].indexOf("|"));
}
}
if(seperator.length==0)
{
return("Nothing found!");
}
else
var found2 = "";
{
for (var j = 0; j < seperator.length; j++)
{
if(u_c_pages[j].substring(seperatorPos[j],u_c_pages[j].length-1).toLowerCase().indexOf(pattern.toLowerCase()) >= 0)
{
found2 = (u_c_pages[j].substring(0,seperatorPos[j]));
break;
}
}
return(found2)
}
}
else
{
// only returned when the user decides to type in nothing
return("Nothing entered!");
}
}
alert(url1_m1(u_c_pages,pattern5));
enjoy the power of regex:
on JSFiddle
pages = ["The first", "An;alternative;page", "Yet another page"];
u_c_pages = [
"www.lboro.ac.uk;"+pages[0],
"www.xyz.ac.uk;"+pages[1],
"www.xyz.ac.uk;"+pages[1],
"www;"+pages[2]
];
var pattern5 = prompt('5) Please enter a search term:');
function url1_m1(u_c_pages,pattern)
{
// escape search pattern
pattern = pattern.toLowerCase().replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
pattern = new RegExp('^([^;]+);.*?' + pattern, 'i');
var result = null;
for(var i=0;i<u_c_pages.length;i++) {
if((result = u_c_pages[i].match(pattern))) {
return result[1];
}
}
return false;
}
alert(url1_m1(u_c_pages,pattern5));
You can use String.split(";") to split a string into segments. The parameter is the seperator.

building a database string

I'm trying to build a database based on some arbitrary data on a website. It's complex and changes for each site so I'll spare the details. Here's basically what I'm trying to do
function level0(arg) { textarea.innerHTML += arg + ' = {'; }
function level1(arg) { textarea.innerHTML += '\n\t' + arg + ': ['; }
function level2(arg) { textarea.innerHTML += arg + ', '; }
And so on. The thing is some level1's don't have any children and I can't get the formatting right.
My three problems are as follows.
The ending commas are going to break in IE (thank you MS)
Empty level1's shouldn't be printed if they don't have any children
Closing /curly?brackets/
HERE'S A DEMO of what I have so far. Notice the ending commas, the empty sub2 which shouldn't be printed, and no closing brackets or braces
Do I need to redesign the entire thing?
Is there also a way to have this all in one function so I don't have to worry if I add another layer?
EDIT
This needs to be done in a string format, I can't build an object and then stringify it, mostly because I need to know which element I'm in the middle of adding to.
Overall it looks that you still might want to build an object, but in case you insist on not building it - here is some sample solution:
function Printer() {
var result = '',
lastLevel = null,
close = {0:'\n}', 1:']', 2:''},
delimiter = {0: ',\n', 1:',\n', 2:','};
function closeLevel(level, noDelimiter) {
if(lastLevel === null)
return;
var l = lastLevel, d = level == lastLevel;
while(l >= level) {
result += close[l] + (l == level && !noDelimiter ? delimiter[l]:'');
l--;
}
}
this.level0 = function(arg) {
closeLevel(0);
result += arg + ' = {\n';
lastLevel = 0;
};
this.level1 = function(arg) {
closeLevel(1);
result += '\t' + arg + ': [';
lastLevel = 1;
};
this.level2 = function(arg) {
closeLevel(2);
result += arg;
lastLevel = 2;
};
this.getResult = function() {
closeLevel(lastLevel, true);
return result;
}
}
var p = new Printer();
p.level0('head');
p.level1('sub1');
p.level2('item1');p.level2('item2');p.level2('item3');
p.level1('sub2');
p.level1('sub3');
p.level2('newthing');
p.level0('head2');
document.getElementById('textarea').value = p.getResult();
You could see it in action here.
I'm not sure why you're building what looks like objects with nested arrays, using string concatenation. Something like this would be much simpler, since it wouldn't require fixing trailing commas, etc:
Edit: I've updated the code to make it keep track of the last level put in.
function Db() {
var level0, level1;
var data = new Object();
this.level0 = function(arg) {
level0 = new Object();
data[arg] = level0;
}
this.level1 = function(arg) {
level1 = new Array();
level0[arg] = level1;
}
this.level2 = function(arg) {
level1.push(arg);
}
this.toString = function() {
var s = '';
for(i in data) {
s += i + '\n';
for(j in data[i]) {
if(data[i][j].length>0) {
s += '\t' + j + ': [' + data[i][j] + ']\n' ;
}
}
}
return s;
}
}
Use like this:
var db = new Db();
db.level0('head');
db.level1('sub1');
db.level2('item1');db.level2('item2');db.level2('item3');
I've tested this in the demo you linked and it works just fine.

jQuery plugin DataTables: How to highlight the current search text?

I have started using the DataTables plugin (v1.6.2) for jQuery(v1.4.2), and I would like to ask you if you know a settings or a plugin that allow me to highlight the text used in search textbox on the filtered rows.
Thank you in advance
I would have to suggest the highlight plugin :)
I'm using this in about the same scenario right now, it's given me no issues thus far.
The usage is pretty simple:
$("#myTable").highlight($("#searchBox").val());
Just put the highlight CSS class in your stylesheet styles like you want and that's it:
.highlight { background-color: yellow }
I know that this question is now over 6 years old and the answers here may helped you at the time of asking. But for people still searching for this, there is a new plugin to integrate mark.js – a JavaScript keyword highlighter – into DataTables: datatables.mark.js.
Usage is as simple as:
$("table").DataTables({
mark: true
});
Here is an example: https://jsfiddle.net/julmot/buh9h2r8/
This is the cleanest way and also gives you options none of the given solutions offers you.
There's now an official DataTables blog article available.
You can use this function by coping this content :
jQuery.fn.dataTableExt.oApi.fnSearchHighlighting = function(oSettings) {
oSettings.oPreviousSearch.oSearchCaches = {};
oSettings.oApi._fnCallbackReg( oSettings, 'aoRowCallback', function( nRow, aData, iDisplayIndex, iDisplayIndexFull) {
// Initialize search string array
var searchStrings = [];
var oApi = this.oApi;
var cache = oSettings.oPreviousSearch.oSearchCaches;
// Global search string
// If there is a global search string, add it to the search string array
if (oSettings.oPreviousSearch.sSearch) {
searchStrings.push(oSettings.oPreviousSearch.sSearch);
}
// Individual column search option object
// If there are individual column search strings, add them to the search string array
if ((oSettings.aoPreSearchCols) && (oSettings.aoPreSearchCols.length > 0)) {
for (var i in oSettings.aoPreSearchCols) {
if (oSettings.aoPreSearchCols[i].sSearch) {
searchStrings.push(oSettings.aoPreSearchCols[i].sSearch);
}
}
}
// Create the regex built from one or more search string and cache as necessary
if (searchStrings.length > 0) {
var sSregex = searchStrings.join("|");
if (!cache[sSregex]) {
var regRules = "("
, regRulesSplit = sSregex.split(' ');
regRules += "("+ sSregex +")";
for(var i=0; i<regRulesSplit.length; i++) {
regRules += "|("+ regRulesSplit[i] +")";
}
regRules += ")";
// This regex will avoid in HTML matches
cache[sSregex] = new RegExp(regRules+"(?!([^<]+)?>)", 'ig');
}
var regex = cache[sSregex];
}
// Loop through the rows/fields for matches
jQuery('td', nRow).each( function(i) {
// Take into account that ColVis may be in use
var j = oApi._fnVisibleToColumnIndex( oSettings,i);
// Only try to highlight if the cell is not empty or null
if (aData[j]) {
// If there is a search string try to match
if ((typeof sSregex !== 'undefined') && (sSregex)) {
this.innerHTML = aData[j].replace( regex, function(matched) {
return "<span class='filterMatches'>"+matched+"</span>";
});
}
// Otherwise reset to a clean string
else {
this.innerHTML = aData[j];
}
}
});
return nRow;
}, 'row-highlight');
return this;
};
inside :
dataTables.search-highlight.js
an call it like this example:
<script type="text/javascript" src="jquery.dataTables.js"></script>
<script type="text/javascript" src="dataTables.search-highlight.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var oTable = $('#example').dataTable();
oTable.fnSearchHighlighting();
} );
</script>
and add this code to you css file:
.filterMatches{
background-color: #BFFF00;
}
<link href="https://cdn.datatables.net/plug-ins/1.10.13/features/mark.js/datatables.mark.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/jquery.mark.js"></script>
<script src="https://cdn.datatables.net/plug-ins/1.10.13/features/mark.js/datatables.mark.js"></script>
$("#tableId").dataTable({
mark: true
});
You can use the following add on
jQuery.fn.dataTableExt.oApi.fnSearchHighlighting = function(oSettings) {
// Initialize regex cache
oSettings.oPreviousSearch.oSearchCaches = {};
oSettings.oApi._fnCallbackReg( oSettings, 'aoRowCallback', function( nRow, aData, iDisplayIndex, iDisplayIndexFull) {
// Initialize search string array
var searchStrings = [];
var oApi = this.oApi;
var cache = oSettings.oPreviousSearch.oSearchCaches;
// Global search string
// If there is a global search string, add it to the search string array
if (oSettings.oPreviousSearch.sSearch) {
searchStrings.push(oSettings.oPreviousSearch.sSearch);
}
// Individual column search option object
// If there are individual column search strings, add them to the search string array
// searchTxt=($('#filter_input input[type="text"]')?$('#filter_input input[type="text"]').val():"");
var searchTxt = $('input[type="search"]').val();
// console.log("txt" + searchTxt);
if ((oSettings.aoPreSearchCols) && (oSettings.aoPreSearchCols.length > 0)) {
for (var i in oSettings.aoPreSearchCols) {
if (oSettings.aoPreSearchCols[i].sSearch) {
searchStrings.push(searchTxt);
}
}
}
// Create the regex built from one or more search string and cache as necessary
/*if (searchStrings.length > 0) {
var sSregex = searchStrings.join("|");
if (!cache[sSregex]) {
// This regex will avoid in HTML matches
cache[sSregex] = new RegExp("("+escapeRegExpSpecialChars(sSregex)+")(?!([^<]+)?>)", 'i');
}
var regex = cache[sSregex];
}*/
if (searchStrings.length > 0) {
var sSregex = searchStrings.join("|");
if (!cache[sSregex]) {
var regRules = "("
, regRulesSplit = sSregex.split(' ');
regRules += "("+ sSregex +")";
for(var i=0; i<regRulesSplit.length; i++) {
regRules += "|("+ regRulesSplit[i] +")";
}
regRules += ")";
// This regex will avoid in HTML matches
cache[sSregex] = new RegExp(regRules+"(?!([^<]+)?>)", 'ig');
}
var regex = cache[sSregex];
}
// Loop through the rows/fields for matches
jQuery('td', nRow).each( function(i) {
// Take into account that ColVis may be in use
var j = oApi._fnVisibleToColumnIndex( oSettings,i);
// Only try to highlight if the cell is not empty or null
// console.log("data "+ aData[j] + " j " + j);
// console.log("data 1 "+ nRow);
if (aData) {
// If there is a search string try to match
if ((typeof sSregex !== 'undefined') && (sSregex)) {
//console.log("here :: "+$(this).text());
this.innerHTML = $(this).text().replace( regex, function(matched) {
return "<span class='filterMatches'>"+matched+"</span>";
});
}
// Otherwise reset to a clean string
else {
this.innerHTML = $(this).text();//aData[j];
}
}
});
return nRow;
}, 'row-highlight');
return this;
};
This solution is working for me.
Note: Currently it does not support individual column filtering, but you just have to uncomment following in the code.
searchTxt=($('#filter_input input[type="text"]')?$('#filter_input input[type="text"]').val():"");
I have tested this with datatables 1.10.2 and jquery 1.9.2 version.
This add on have better feature for highlighting search text. if you have created datatable in a dialog , then on dialog reopen you need to reinitialize datatable.
In DatatableHighlighter.js
jQuery.fn.dataTableExt.oApi.fnSearchHighlighting = function(oSettings) {
// Initialize regex cache
oSettings.oPreviousSearch.oSearchCaches = {};
oSettings.oApi._fnCallbackReg( oSettings, 'aoRowCallback', function( nRow, aData, iDisplayIndex, iDisplayIndexFull) {
// Initialize search string array
var searchStrings = [];
var oApi = this.oApi;
var cache = oSettings.oPreviousSearch.oSearchCaches;
// Global search string
// If there is a global search string, add it to the search string array
if (oSettings.oPreviousSearch.sSearch) {
searchStrings.push(oSettings.oPreviousSearch.sSearch);
}
// Individual column search option object
// If there are individual column search strings, add them to the search string array
// searchTxt=($('#filter_input input[type="text"]')?$('#filter_input input[type="text"]').val():"");
var searchTxt = $('input[type="search"]').val();
// console.log("txt" + searchTxt);
if ((oSettings.aoPreSearchCols) && (oSettings.aoPreSearchCols.length > 0)) {
for (var i in oSettings.aoPreSearchCols) {
if (oSettings.aoPreSearchCols[i].sSearch) {
searchStrings.push(searchTxt);
}
}
}
// Create the regex built from one or more search string and cache as necessary
if (searchStrings.length > 0) {
var sSregex = searchStrings.join("|");
if (!cache[sSregex]) {
var regRules = "("
, regRulesSplit = sSregex.split(' ');
regRules += "("+ sSregex +")";
for(var i=0; i<regRulesSplit.length; i++) {
regRules += "|("+ regRulesSplit[i] +")";
}
regRules += ")";
// This regex will avoid in HTML matches
cache[sSregex] = new RegExp(regRules+"(?!([^<]+)?>)", 'ig');
//cache[sSregex] = new RegExp(regRules+"", 'ig');
}
var regex = cache[sSregex];
}
// Loop through the rows/fields for matches
jQuery('td', nRow).each( function(i) {
// Take into account that ColVis may be in use
var j = oApi._fnVisibleToColumnIndex( oSettings,i);
if (aData) {
// If there is a search string try to match
if ((typeof sSregex !== 'undefined') && (sSregex)) {
//For removing previous added <span class='filterMatches'>
var element = $(this);//convert string to JQuery element
element.find("span").each(function(index) {
var text = $(this).text();//get span content
$(this).replaceWith(text);//replace all span with just content
}).remove();
var newString = element.html();//get back new string
this.innerHTML = newString.replace( regex, function(matched) {
return "<span class='filterMatches'>"+matched+"</span>";
});
}
// Otherwise reset to a clean string
else {
//For removing previous added <span class='filterMatches'>
var element = $(this);//convert string to JQuery element
element.find("span").each(function(index) {
var text = $(this).text();//get span content
$(this).replaceWith(text);//replace all span with just content
}).remove();
var newString = element.html();
this.innerHTML = newString;//$(this).html()//$(this).text();
}
}
});
return nRow;
}, 'row-highlight');
return this;
};
and call it like this ....
$("#button").click(function() {
dTable = $('#infoTable').dataTable({"bPaginate": false,"bInfo" : false,"bFilter": true,"bSort":false, "autoWidth": false,"destroy": true,
"columnDefs": [
{ "width": "35%", "targets": 0 },
{ "width": "65%", "targets": 1 }
]});
$(".dataTables_filter input[type='search']").val('');
$("span[class='filterMatches']").contents().unwrap();
dTable.fnSearchHighlighting();
$("span[class='filterMatches']").contents().unwrap();
$("#AboutDialog").dialog('open');
});

Categories