I have a table with a bunch of data in it. Currently, my code compares textfield input to the data in the table. If there's a match, it will show that particular table row. Here's my code:
$(document).on('keyup','#filterText',function(){
$('.all').hide(); // hide everything
$('tfoot').hide(); // hide everything
var s = $(this).val().toLowerCase(); //get input string
if(s==''){$('.all').show(); $('tfoot').show();}; // if no input then show everything
$('#report tbody tr td').each(function(i,td) {
//go through each table cell and compare
if($(td).text().toLowerCase().indexOf(s)!==-1){
$(td).closest('tr').show(); // show table row
}
});
}); //.but_filterText
This works great. But now, I need to modify this so that a user could do multiple searches at the same time, separated by a comma. So here's what I did and nothing happens:
$(document).on('keyup','#filterText',function(){
$('.all').hide();
$('tfoot').hide();
var s = $(this).val().toLowerCase().split(',');
if(s === undefined || s.length == 0){
$('.all').show(); $('tfoot').show();
};
$('#report tbody tr td').each(function(i,td) {
if(s.indexOf($(td).text().toLowerCase())!==-1){
$(td).closest('tr').show();
}
});
}); //.but_filterText
Seems like it should work but can't get it going. What am I doing wrong. Thank you
I thinks the issue is because in the input field you type space after comma, e.g. text 1, text 2 instead of text 1,text 2
i made a small (similar to yours code) example: (in this example you can type with or without space, since it will be replaced)
$('[name="search"]').on('keyup', function() {
var $tds = $('td');
var s = this.value.toLowerCase().replace(/\,\s/,',').split(',');
// consider replacing comma+space (/\,\s/) with just a comma
// and also i would recommend using filter function for finding matches,
// it will return an array of matched elements, empty if there is no match
$tds = $tds.filter(function(i, td) {
return s.indexOf($(td).text().toLowerCase()) >=0;
});
$tds.addClass('selected');
});
Here is the jsfillde - http://jsfiddle.net/zqdbso1w/1/
UPDATE (based on your comment)
Here is the jsfillde - http://jsfiddle.net/zqdbso1w/3/
simply make second iteration to seek for a substring in haystack
$('[name="search"]').on('keyup', function() {
var $tds = $('td');
var s = this.value.toLowerCase().replace(/\,\s/,',').split(',');
$tds.removeClass('selected');
$tds.each(function() {
var text = $(this).text().toLowerCase();
var r = s.filter( function(t) {
if (!t.length) return false;
return text.indexOf(t) >= 0;
});
if (r.length) $(this).addClass('selected');
});
});
UPDATE regex should be global, and remove all spaces after all commas
Here is the jsfiddle - http://jsfiddle.net/zqdbso1w/4/
Related
I am stuck in jquery Data table. if we use jquery data table then it provide by default search option. But problem is that if i search particular record and if content is not match or i found single record. then i need to remove sorting icon. it will work but as i press back space and remove searching content then as usual it display all records. But now sortable icon is disable it needs to enabled once again then what is the solution for that.
This is function call:-
$('#datatable-information').on('draw.dt', function () {
disableSortingSearchOption(oTable, 'datatable-information_filter input');
This is Function Defination:-
function disableSortingSearchOption(oTables, tableClass) {
if (oTables != null) {
var rowCount = oTables.fnSettings().fnRecordsDisplay();
{
if (rowCount == 0 || rowCount == 1) {
var oSettings = oTables.fnSettings();
//Remove sort icon
$('.DataTables_sort_icon').remove();
//Remove hand cursor
$('.datatable th').css('cursor', 'default');
//Iterate through each column and disable sorting
$('.' + tableClass + ' th').each(function (index) {
if ((oSettings.aoColumns[index]) != undefined) {
oSettings.aoColumns[index].bSortable = false;
}
});
}
}
}
}
Here is a simple way to remove the sorting arrows on the table headers and change the pointer to default when the drawed table has 1 line or less.
On more than one line, the table sorting and the pointer comes back to "normal".
My solution is quite different than the code you provided.
function disableSortingSearchOption(oTables) {
if (oTables != null) {
var colCount = 0;
$(oTables).find('th').each(function(){
colCount++;
});
//console.log(colCount+" colunms");
var rowCount = 0;
$(oTables).find('td').each(function(){
rowCount++;
});
rowCount = rowCount/colCount;
//console.log(rowCount+" rows");
if (rowCount <= 1) {
//Remove hand cursor
$(oTables).find('th').css('cursor', 'default');
//Remove sort arrows
$(oTables).find('th').removeClass('sorting');
}else{
//Add hand cursor
$(oTables).find('th').css('cursor', 'pointer');
//Add sort arrows
$(oTables).find('th').addClass('sorting');
}
}
}
We need to know the row amount...
To achieve this, we first count the column amount and the whole table's td amount.
The row amount is the td amount divided by the column amount.
Based on this number, we can add or remove the sorting class on all th and set the cursor.
Note that when there is no result, there is still one line to show "No matching records found". But since there is only 1 td in this case... divided by the colunm count, we have to think about "one or less line".
;)
Have a look at this CodePen.
I have a table where the first column will always turn out to be unique. So when I remove the duplicate rows none would be removed. So i want to remove duplicates by eliminating the first row in the duplicate check. Each cell in the table may contain more than one value.
Input Table
Output table
I found the script for eliminating the duplicate rows from other question. But that is not what I am looking for. This question has something similar, but it is done only on the first column. I do not know how I can eliminate the first column from being accessed.
Script
<script>
var seen = {};
$('table tr').each(function() {
var txt = $(this).text();
if (seen[txt])
$(this).remove();
else
seen[txt] = true;
});
</script>
What I am trying to achieve
I would first eliminate the duplicate elements within the cell and then eliminate the rows with duplicate values. So from the input table above, in the column C_fb 4000 being written twice would be eliminated and then checked for duplicate rows.
Combined not selector and first selector, your code works!
var seen = {};
$('table tr').each(function() {
var txt = $(this).find("td:not(:first)").text();
if (seen[txt])
$(this).remove();
else
seen[txt] = true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><td>id1</td><td>aaaaa</td><td>ccccccccc</td></tr>
<tr><td>id2</td><td>bbbbb</td><td>dddddddd</td></tr>
<tr><td>id3</td><td>bbbbb</td><td>dddddddd</td></tr>
<tr><td>id4</td><td>bbbbb</td><td>dddddddd</td></tr>
</table>
Use the :not and the :first jQuery-Selector. source: here
var seen = {};
$('table tr:not(:first)').each(function() {
var txt = $(this).text();
if (seen[txt])
$(this).remove();
else
seen[txt] = true;
});
On a random break I found myself wondering if it would be possible to use jQuery to determine a single character within a sentence when it is clicked on.
For example:
This
When the user clicks on first h, jQuery would return this to me.
The only way I could think of doing this would be to wrap each character within the sentence in a span with a class of its letter such as the following example:
<span class="clickable T">T</span>
<span class="clickable h">h</span>
<span class="clickable i">i</span>
<span class="clickable s">s</span>
Followed by a $('.clickable').click(function()) that would return its second class.
My question is: is this the most efficient way to do this?
Obviously wrapping every single letter of the document in span tags is not efficient.
I was able to spin something up that works in Chrome at least. Basically, when you click on a letter, it then triggers a double clicks which selects the word. We get the selection which actually gives us the text of the entire target element. From that, we get the letter that was clicked. We remove the selection and do what we want with the letter.
Fiddle here
$(function(){
$(document).click(function(e){
var target = e.target;
$(target).dblclick();
}).dblclick(function(){
var selection,
node,
text,
start,
end,
letter;
if (window.getSelection) {
selection = document.getSelection();
node = selection.anchorNode;
if (node.nodeType === 3) {
text = node.data;
start = selection.baseOffset;
end = selection.extentOffet;
if (!isNaN(start)) {
letter = text.substr(start, 1);
}
}
window.getSelection().removeAllRanges()
} else if(document.selection) {
//continue work here
}
if (letter) {
alert(letter);
}
});
});
You could return the innerHTML as well with:
$('.clickable').on('click', function(){
alert($(this).html());
});
As for a more efficient way to do it...maybe try this:
in Javascript/jQuery, how to check a specific part of a string and determine if it is a whitespace or letter?
You can do it with this script
$('.clickable').on('click', function(){
var html = $(this).text(); // if you want the text inside the span
var index = $(this).index(); // if you want the position among siblings
var classes = $(this).attr('class').split(" ");
var secondClass = getSecondClass(classes);
});
function getSecondClass(classArray){
if(classArray.length<2){
return null;
}else{
return classArray[1];
}
}
I've also included the html and index variables if you want to do something else with the clicked element.
Basically you split the classes of the element by spaces and then check if the array has less than two elements, in that case it returns null, otherwise it returns the second element.
jsFiddle
Well wrapping all text dyanamically with span tag , it is possible what you were looking for
JS
$(function(){
var lengthText = $('#singlecharacter').text().length;
var textValue = $('#singlecharacter').text();
var textArray = textValue.split('');
var newText = new Array();
for (var i = lengthText - 1; i >= 0; i--) {
newText[i] = "<span class='sp'>"+textArray[i]+"</span>";
};
$('#singlecharacter').html(newText);
$('.sp').click(function()
{
alert($(this).text());
});
});
HTML
<div id='singlecharacter'>THIS</div>
DEMO JSFIDDLE
If I am looping through elements in a table - say a hidden field of class "pmtos" - how do I get a reference to the text field (input) within the same cell in the table?
jQuery is:
// Loop through each hidden field, which holds the outstanding amount
$(".pmtos").each(function () {
var os = $(this).val();
//
//find text box in same cell - and populate with some value
//
//
});
Thank you for any guidance in getting this working.
Mark
Here's a solution to the question before it was edited (as requested):
$('#allocate').click(function () {
var recd = parseFloat( $('#pmtRecd').val() );
$('input.pmtallocated').each(function() {
var value = parseFloat( $(this).parent().prev().text() );
this.value = (recd >= value) ? value : recd;
recd = recd - this.value;
if (recd == 0) {
return false;
}
});
});
Note: This doesn't rely on the hidden input. It takes the text from the td in the second column.
Here's the fiddle
To answer the question post-edit
You can use siblings('.pmtallocated') or prev('.pmtallocated') to get the input. Using siblings() would probably be the better of the two as it doesn't rely on pmtallocated coming directly before pmtos in the markup:
$(this).siblings('.pmtallocated').val()
Try
// Loop through each hidden field, which holds the outstanding amount
$(".pmtos").each(function () {
var os = $(this);
var cell = os.parent(); // gets the parent, i.e. the table cell
var input = cell.find('input')[0];
});
You could use $(this).closest('input')
Check this out. may works for you.
$(".pmtos").each(function () {
var os = $(this).val();
var input = $(this).closest('td').find('input[type=text]');
});
There is one data table with two rows, as per below image
When user click on 2bit it should highlight that TD in that column only. I achieved this using jQuery for one check box selection, but when multiple check box selection like 2 and 4 it should highlight both the TD.
http://jsbin.com/exazoh/edit#preview working example for single value highlight.
Code: http://jsbin.com/exazoh/2/edit
Try the following function:
jQuery(function() {
// on change of an input with a name starting with "bit-select"...
jQuery('input[name^="bit-select"]').change(function(){
var checked = this.checked,
val = this.value,
column = $(this).closest("th").index() + 1;
// for each td in the current column
jQuery("#tableData tr.data td:nth-child(" +
column + ")").each(function() {
var $td = $(this);
// does the current td match the checkbox?
if ($td.text() == val) {
if (checked)
$td.addClass("jquery-colorBG-highLight");
else
$td.removeClass("jquery-colorBG-highLight");
}
});
});
});
I had to add the value attributes to the second set of checkboxes.
Working demo: http://jsbin.com/exazoh/4/edit#preview
Or the short version, since I notice you were using .filter() originally:
jQuery(function() {
jQuery('input[name^="bit-select"]').change(function(){
var method = this.checked ? "addClass" : "removeClass",
val = this.value;
jQuery("#tableData tr.data td:nth-child("+($(this).closest("th").index()+1)+")")
.filter(function(){return $(this).text()==val;})[method]("jquery-colorBG-highLight");
});
});
Demo: http://jsbin.com/exazoh/5/edit