I have the following code below... It takes a search field, and quickly searches the table for matching items, and hides all the other results. Right now this code works for a single search field (with class .search), and a single table (with id #SearchableTbl).
$(document).ready(function(){
$('.search').on('keyup',function(){
var searchTerm = $(this).val().toLowerCase();
$('#SearchableTbl tbody tr').each(function(){
var lineStr = $(this).text().toLowerCase();
if(lineStr.indexOf(searchTerm) === -1){
$(this).hide();
}else{
$(this).show();
}
});
});
});
I don't know javascript, so I'm not sure how to make this function work for multiple tables. So, if the first search field was .search1 (and not just .search), and the second was .search2. And, the tables being searched were #SearchableTbl1 and #SearchableTbl2 (respectively).
Can someone help me modify the code so this works with many (not just 2) tables? As I said, I don't know javascript (but I do know a little PHP), so I'm trying to do something like this (below is a mish-mash of PHP and Javascript, which definitely wont work, but should get my point across) ....
$(document).ready(function(){
for($var=1; $var<10; $var++;) {
$('.search($var)').on('keyup',function(){
var searchTerm = $(this).val().toLowerCase();
$('#SearchableTbl($var) tbody tr').each(function(){
var lineStr = $(this).text().toLowerCase();
if(lineStr.indexOf(searchTerm) === -1){
$(this).hide();
}else{
$(this).show();
}
});
});
}
});
Thanks!
With jQuery it depends on your dom structure, so wrap the table and search input (or anything else for that "data table" component) in a div, then the simple fact you're inputting into a specific input you can use that to find the parent element then find() the table.
$(document).ready(function(){
$('.data-table input').on('keyup',function(){
// find the parent
var parent = $(this).closest('.data-table')
var searchTerm = $(this).val().toLowerCase();
$(parent).find('table tbody tr').each(function(){
var lineStr = $(this).text().toLowerCase();
if(lineStr.indexOf(searchTerm) === -1){
$(this).hide();
}else{
$(this).show();
}
});
});
});
<div class="data-table">
<input type="text"/>
<table>
...
<table>
</div>
Related
I'm new to jQuery and need help on searching for user-typed element within a table. I wrote this in JS, but have a problem writing in using jQuery.
When the element is found, the other rows in the table with the same class name should be visible and other rows should be hidden:
$(document).ready(function()
{
search(".site-table", "#recordInput");
console.log("Document is ready");
}
);
function search(search_table, search_field)
{
// Searching for an item specified in search_field within a table
$(search_field).on("keyup", function()
{
var target_text = $(this).val().toLowerCase();
//Hide everything first
$(search_table).find('tr').addClass(".hidden");
$(search_table).find('tr').each(function(index, element){
// For each row, find out if the row has the target_text in it
$element:contains($target_text).each(function(index, element){
$(element).removeClass(".hidden");
});
// for each row with the target text in it, find other rows with this rows class name in their class name and show them. Any other row should be hidden
});
Any help is appreciated.
EDIT 1:
So, here is the editted code after the comments. I still cannot get it working:
$(document).ready(function()
{
search(".site-table", "#recordInput");
console.log("Document is ready");
}
);
function search($search_table, $search_field)
{
console.log("Starting to search...");
$($search_field).on("keyup", function()
{
// Heighlight the search field
$(this).css('border', '1px solid red');
$search_text = $(this).val().toLowerCase();
// 1st method:
$search_result = $($search_table).find('tbody tr').text().toLowerCase().indexOf($search_text > -1); // Does not work! Nothing is found when there is a match
console.log("Search Result: ", $search_result);
// 2nd method:
$($search_table).find('tr').each(function(index, element){
// For each row, toggle the hidden class if the row contains the search text
$(this).toggleClass('hidden', $(this).text().toLowerCase().indexOf($search_text > -1));
});
// 3rd method:
var found = $($search_table).find('tbody tr').filter(function() {
return $(this).text().toLowerCase() == $search_text;
});
console.log("found: ", found);
});
}
None of these methods works! What am I doing wrong in each method?
Your problem is about using the indexOf. What you must put between the parentheses is only the searching text and > -1 must be out. See this sample:
var its_ok = $('div').first().html().indexOf('b') > -1
console.log('first one: ', its_ok)
var its_not_ok = $('div').first().html().indexOf('b' > -1)
console.log('second one: ', its_not_ok)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>abcd</div>
What you have done is the second one that is not true way of using the indexOf.
I have a table with two links in each row, like this:
<table class="list">
...
<td>
756
</td>
<td>
some link
</td>
<td>some text</td>
<td>some more text</td>
...
</table>
The first link always has an ID, which starts with the same characters, followed by a random number. The second link does not have an ID. I would like to get the inner html of the first link when either link is clicked.
Demo here: http://codepen.io/sol_b/pen/XNqOgN
I have tried a few things using Jquery. This is what I have so far:
$('.list').find("a").click(function(){
$(this).each(function(){
if ($(this).attr('id') !=undefined) {
var number = $(this).html();
alert (number);
} else if ($(this).attr('id') == undefined) {
var number = $(this).prev('a').html();
alert (number);
}
})
});
This works for the first link, however it returns undefined for the second. I'm not sure why using .prev isn't working.
Any help much appreciated!
(note that I'm unable to change the HTML structure)
Do a single click event, go to the parent tr find the link with the id starting with "abcdefg", get the text
$('.list tr a').click(function(){
var text = $(this).closest('tr').find('a[id^="abcdefg"]').text();
console.log(text)
});
the demo: http://codepen.io/anon/pen/qqKrjE?editors=1111
Just use $('.list tr td a').first().html() to get the first link of the table.
So, that's all you need:
$(function(){
$('.list').find("a").click(function(){
if ($(this).attr('id') !=undefined) {//Links with id (1st column)
var number = $(this).html();//Get clicked link
alert (number);
} else if ($(this).attr('id') == undefined) {//Links with no id (2nd column)
var number = $('.list tr td a').first().html();//Get first link
alert (number);
}
});
})
.prev() returns previous adjacent sibling. If no previous sibling exists, or if the previous sibling element does not match a supplied selector, an empty jQuery object is returned.
In ur case changing .prev() to .parent().prev().children() will help.
http://codepen.io/anon/pen/XNYMNG?editors=1010
Your code will work with follow code,
$(function(){
$('.list').find("a").click(function(){
$(this).each(function(){
if ($(this).attr('id') !=undefined) {
var number = $(this).html();
alert (number);
} else if ($(this).attr('id') == undefined) {
//Little bit change here
var number = $(this).parent().prev().find('a').html();
alert (number);
}
})
});
})
When a link is clicked, you should go to the parent "tr", then select the first link in it, like this :
$(this).closest('tr').find('a').eq(0);
That way you'll always have the first link in the row you clicked.
try something like this -
$(document).ready(function () {
$('.list').find("a").click(function () {
if (this.id == "") {
alert(($($($($(this).parent()[0]).parent()[0]).children()[0]).children()[0]).innerHTML)
}
});
});
I'm trying to make a filter on screen, by just hiding what doesn't meet the requirements.
This what I've come up with so far. I'm not sure what I am doing wrong.
jQuery :
jQuery('#searchBox').on('keyup change', function() {
var search = $('#searchBox').val();
//for each h4
$('h4').each(function(){
var h4id = $(this).attr('id');
if ($(h4id).contains(search))
$(this).show();
else
$(this).hide
});
HTML :
<input type="search" name="search" id="searchBox"/>
<h4 id="Adminstrator">Administrator</h4>
<h4 id="John,Smith">John Smith</h4>
<h4 id="Jane,Smith">Jane Smith</h4>
(I'm using jQuery 1.9.1)
(So, if I start typing Smith, "Administrator" h4 should disappear.
.contains will not give you the text content of the selector. It will only search for elements inside the selector.
Try this approach .. This can be lot more optimized
jQuery('#searchBox').on('keyup change', function () {
var search = $('#searchBox').val().toLowerCase();
$('h4').hide();
$('h4').each(function () {
var h4id = $(this).attr('id'),
$text = $('#'+ h4id).text().toLowerCase();
if($text.indexOf(search) > -1)
$(this).show();
});
});
Make sure your id's are unique.
Next is your id's should not contain , in them
JSFIDDLE
Try this:-
Simple one, but case sensitive though
Demo
jQuery('#searchBox').on('keyup change', function() {
var search = $('#searchBox').val();
$('h4').hide();
$('h4[id*='+ search + ']').show();
});
See if this helps. I won't use id for storing the string comparison since name can be same for multiple people and you might end up having multiple h4s with same id. SO i am using data-attribute and jquery data here.
Demo
jQuery('#searchBox').on('keyup change', function() {
var search = $('#searchBox').val();
$('h4').hide().filter(function(_,oj){
return $(oj).data('key').toLowerCase().indexOf(search.toLowerCase()) > -1;
//if your are trying to match the text() then do
//return $(oj).text().toLowerCase().indexOf(search.toLowerCase()) > -1;
}).show();
});
Fixing your code would mean this. There is no contains function and couple of other typos.
Demo
jQuery('#searchBox').on('keyup change', function() {
var search = $('#searchBox').val();
//for each h4
$('h4').each(function(){
var h4id = this.id;
if (h4id.indexOf(search) > -1)
//if your are trying to match the text() then do
//if ($('#'+h4id).text().indexOf(search) > -1)
$(this).show();
else
$(this).hide();
});
});
Try a regex based solution
jQuery('#searchBox').on('keyup change', function() {
var search = $(this).val();
var regex = new RegExp(search, 'i');
//for each h4
$('h4').hide().filter(function(){
return regex.test(this.id)
}).show();
});
Demo: Fiddle
Just using jQuery attribute selector,see here,just two line code will be enough.
Demo:
//for each h4
var h4id = $(this).attr('id');
$("h4").hide().filter("[id*=" + h4id + "]").show();
How can I build a simple table filter with good effect using jQuery? I don't mind about pagination.
list -> select data of database.
I do not want to use a plugin, I prefer the use of short code.
Example:
$('#inputFilter').keyup(function() {
var that = this;
$.each($('tr'),
function(i, val) {
if ($(val).text().indexOf($(that).val()) == -1) {
$('tr').eq(i).hide();
} else {
$('tr').eq(i).show();
}
});
});
CHECH THIS
I don't normally help out with this, but I got bored this morning..
http://jsfiddle.net/hHJxP/
I know it's kinda late but hope this code helps.
<script>
$(document).ready(function(){
$("#yourInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#yourTableId tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>
Try testing the innerHTML of the row to the value of the input field, showing / hiding the content depending on the test-result.
$('#test').bind('keyup', function() {
var s = new RegExp(this.value);
$('tr').each(function() {
if(s.test(this.innerHTML)) $(this).show();
else $(this).hide();
});
});
JSFIDDLE with example table and input field.
edit
It might be better to use .text() instead of innerHTML. Performancewise innerHTML would be better, but .text() doesn't accept the html-tags as valid search results. JSFIDDLE #2.
I have a small requirement,
We have restore the textbox data that was cleared previously.
Below is my HTMl code
<table>
<tr><td><input type="textbox"></td></tr>
<tr><td><input type="checkbox"></td></tr>
</table>
Here is my JQuery Code
$('TABLE TR TD').find(':checkbox').change(function()
{
if($(this).prop('checked'))
{
$(this).parents('TR').siblings('TR').find('input').val("")
}
if(!$(this).prop('checked'))
{
$(this).parents('TR').siblings('TR').find('input').val(?)
}
});
My Requirement is to clear the textbox content if checkbox is checked. And if i deselect it the textbox should be restored with previous data.
Please someone help me.
Use a global variable to store the previous data -
var prevData;
then modify your code this way -
$('TABLE TR TD').find(':checkbox').change(function()
{
if($(this).prop('checked'))
{
var $element = $(this).parents('TR').siblings('TR').find('input')
prevData = $element.val();
$element.val("");
}
else
{
$(this).parents('TR').siblings('TR').find('input').val(prevData);
}
});
When the checkbox is being checked, before clearing the value, store it using the jQuery .data() API.
<table>
<tr><td><input type="text"></td></tr>
<tr><td><input type="checkbox"></td></tr>
</table>
$('input:checkbox').change(function() {
var input = $(this).closest('table').find('input[type="text"]');
if ($(this).prop('checked')) {
input.data('text', input.val());
input.val('');
} else {
input.val(input.data('text'));
}
});
A demo which works if there were multiple pairs, so long as they exist in separate <table> parents. You could change the finder to get the previous sibling if that were not the case. This uses no global variables which are not really best practice - How to avoid global variables in JavaScript?.
Edit: Updated demo based on your other question Keydown event is not working properly but this will only for key events and not if someone pastes text into the <input>.
I'd suggest something a little less reliant on the mark-up remaining the same (though it does require that the checkbox follows the text input):
var prevData, textInputIndex;
$('input:checkbox').change(
function(){
thisIndex = ($(this).index('table input') - 1);
textInput = $('table input').eq(thisIndex);
if ($(this).is(':checked')) {
prevData = $(textInput).eq(thisIndex).val();
$(textInput).eq(thisIndex).val('');
}
else {
$(textInput).eq(thisIndex).val(prevData);
}
});
JS Fiddle demo.
Edited to remove the problem of having only one variable to store the text-input value:
var $textInputs = $('table input:text');
var prevData, textInputIndex, affectedTextInputIndex, textInputValues = [];
$('input:checkbox').change(
function(){
affectedTextInputIndex = $(this).index('table input') - 1;
textInputIndex = $('table input').eq(affectedTextInputIndex).index('table input:text');
if ($(this).is(':checked')) {
textInputValues[textInputIndex] = $textInputs.eq(textInputIndex).val();
$textInputs.eq(textInputIndex).val('');
}
else {
$textInputs.eq(textInputIndex).val(textInputValues[textInputIndex]);
}
});
JS Fiddle demo.
Edited to remove the explicit requirement that the input elements be contained in a table:
var $textInputs = $('input:text');
var prevData, textInputIndex, affectedTextInputIndex, textInputValues = [];
$('input:checkbox').change(
function(){
affectedTextInputIndex = $(this).index('input') - 1;
textInputIndex = $('ul input').eq(affectedTextInputIndex).index('input:text');
if ($(this).is(':checked')) {
textInputValues[textInputIndex] = $textInputs.eq(textInputIndex).val();
$textInputs.eq(textInputIndex).val('');
}
else {
$textInputs.eq(textInputIndex).val(textInputValues[textInputIndex]);
}
});
JS Fiddle demo.
References:
:checkbox selector.
change().
is().
:checked selector.
index().
val().