jQuery filter for table - javascript

I have created a table but somehow now able to filter the row. Its giving me error as cannot read property split. Here is the link to my fiddle file. Any help would be great. Thanks in advance.
$("#crudtable_filter").keyup(function () {
//split the current value of searchInput
var data = this.value.split(" ");
//create a jquery object of the rows
var jo = $("#crudtable").find("tr");
if (this.value == "") {
jo.show();
return;
}
//hide all the rows
jo.hide();
//Recusively filter the jquery object to get results.
jo.filter(function (i, v) {
var $t = $(this);
for (var d = 0; d < data.length; ++d) {
if ($t.is(":contains('" + data[d] + "')")) {
return true;
}
}
return false;
})
//show the rows that match.
.show();
}).focus(function () {
this.value = "";
$(this).css({
"color": "black"
});
$(this).unbind('focus');
}).css({
"color": "#C0C0C0"
});

Working fiddle: http://jsfiddle.net/sofqjbrg/3/
Explanation:
In order to get the value of the element that rigger the event, you need to use $(event.target).val().
For the difference between $(event.target) and $(this), please refer to Difference between $(this) and event.target?
PS: Your focus event is registered to the wrong element.

Related

Filtering results in a table

I have a PHP page and a table where I fill it up with data from the database. I have a search field on top of the table where I would like to filter rows as I am typing.
Here is my Javascript
$('#system-search').keyup( function()
{
var that = this;
// affect all table rows on in systems table
var tableBody = $('.table table-filter tbody');
var tableRowsClass = $('.table table-filter tbody tr');
$('.search-sf').remove();
tableRowsClass.each( function(i, val)
{
//Lower text for case insensitive
var rowText = $(val).text().toLowerCase();
var inputText = $(that).val().toLowerCase();
if(inputText != '')
{
$('.search-query-sf').remove();
tableBody.prepend('<tr class="search-query-sf"><td colspan="6"><strong>Searching for: "'
+ $(that).val()
+ '"</strong></td></tr>');
}
else
{
$('.search-query-sf').remove();
}
if( rowText.indexOf( inputText ) == -1 )
{
//hide rows
tableRowsClass.eq(i).hide();
}
else
{
$('.search-sf').remove();
tableRowsClass.eq(i).show();
}
});
//all tr elements are hidden
if(tableRowsClass.children(':visible').length == 0)
{
tableBody.append('<tr class="search-sf"><td class="text-muted" colspan="6">No entries found.</td></tr>');
}
});
Sorry for the bad code and formatting I can't seem to understand how to format it properly..
https://stackoverflow.com/a/19696936/1406155
You are using a bit too much code for that. First place an input field like this
<input type="text" id="search" placeholder="Search">
and use the below function for search
$("#search").keyup(function () {
var value = this.value.toLowerCase().trim();
$("table tr").each(function (index) {
if (!index) return;
$(this).find("td").each(function () {
var id = $(this).text().toLowerCase().trim();
var not_found = (id.indexOf(value) == -1);
$(this).closest('tr').toggle(!not_found);
return not_found;
});
});
});

Function to display returned results count isn't working as expected

My jQuery checkbox filter works normally:
http://jsfiddle.net/EducateYourself/Lmehmj26/3/
Under checkbox form I want to show the number of results. It is 7 by default.
When I filter the results, it does not show the correct number of displayed results.
Could you please help me to find my mistake?
I commented the lines in my jsfiddle code where I added variable n to achieve the result I want.
$('.category').on('change', function () {
var n; //declare variable n
var category_list = [];
$('#filters :input:checked').each(function () {
var category = $(this).val();
category_list.push(category);
});
if (category_list.length == 0) {
$('.resultblock').show();
} else {
$('.resultblock').hide();
});
$('#count').text(n); // change the results qunatity
}
});
The problem is that you are incrementing n multiple times for a single element if it contains multiple matching tags.
You should only increment n once, at most, for each element:
Updated Example
$('.resultblock').each(function() {
var item = $(this).data('tag'),
itemArray = item.split(' '),
hasTag = false;
for (var i = 0; i < category_list.length; ++i) {
if (itemArray.indexOf(category_list[i]) >= 0) {
hasTag = true;
}
}
if (hasTag) {
$(this).show();
n++; // Only increment n once, at most, for each element.
}
});
Here is a cleaner, simplified version of your code:
Updated Example
$('.category').on('change', function() {
var categoryList = $('#filters :input:checked').map(function() {
return this.value;
}).get();
var count = 0;
$('.resultblock').hide().each(function() {
var itemTagsArray = $(this).data('tag').split(' ');
var hasTag = false;
categoryList.forEach(function(tag) {
if (itemTagsArray.indexOf(tag) > -1) {
hasTag = true;
}
});
if (hasTag) {
$(this).show();
count++;
}
});
$('#count').text(count);
});
You're counting doubles, a very easy fix is to add a check for visibility in your for loop like so
for (i = 0; i < category_list.length; ++i) {
if (itemArray.indexOf(category_list[i]) >= 0 && !$(self).is(":visible")) {
$(self).show();
n=n+1; //increase the value of n if found a result
}
}
As shown in this fiddle, that works
As a sidenote, your numbering breaks when you've selected one or more checkboxes and then deselect all. To prevent this you should change your check if there's been any checkboxes checked to
if (category_list.length == 0) {
$('.resultblock').show();
$('#count').text($('.resultblock').length);
}

Javascript Case Sensitive filter

I'm using the script below to filter though results in a table. Only the problem is that it is case sensitive. How would I go about making it non-case sensitive?
<script>
$(document).ready(function() {
$("#searchInput").keyup(function(){
//hide all the rows
$("#fbody").find("tr").hide();
//split the current value of searchInput
var data = this.value.split(" ");
//create a jquery object of the rows
var jo = $("#fbody").find("tr");
//Recusively filter the jquery object to get results.
$.each(data, function(i, v){
jo = jo.filter("*:contains('"+v+"')");
});
//show the rows that match.
jo.show();
//Removes the placeholder text
}).focus(function(){
this.value="";
$(this).css({"color":"black"});
$(this).unbind('focus');
}).css({"color":"#C0C0C0"});
});
</script>
http://jsfiddle.net/baeXs/ and http://css-tricks.com/snippets/jquery/make-jquery-contains-case-insensitive/ will help you out
$.expr[":"].containsNoCase = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
Can do somthing like this with filter():
$.each(data, function (i, v) {
v = v.toLowerCase();
jo.filter(function () {
var txt = $(this).text().toLowerCase();
return txt.indexOf(v) > -1;
}).show();
})
I'd probably change the filter:
$.each(data, function(i, v) {
jo = jo.filter(function() {
return $(this).text().toLowerCase().indexOf(v.toLowerCase()) > -1;
});
});
$(document).ready(function() {
$("#searchInput").keyup(function(){
//hide all the rows
$("#fbody").find("tr").hide();
//split the current value of searchInput
var data = this.value.toLowerCase().split(" ");
//create a jquery object of the rows
var jo = $("#fbody").find("tr");
//Recusively filter the jquery object to get results.
$.each(data, function(i, v){
jo = jo.filter("*:contains('"+v.toLowerCase()+"')");
});
//show the rows that match.
jo.show();
//Removes the placeholder text
}).focus(function(){
this.value="";
$(this).css({"color":"black"});
$(this).unbind('focus');
}).css({"color":"#C0C0C0"});
});

Drag and Drop div into table and get the data value

I set the div data value in table cells, what I want is how to get the div data value, while drop.
In my code, I set the data in the table like this
<script type="text/javascript">
function createDynamicTable(tbody, rows, cols) {
if (tbody == null || tbody.length < 1) return;
for (var r = 1; r <= rows; r++) {
var trow = $("<tr>");
for (var c = 1; c <= cols; c++) {
var cellText = "Cell " + r + "." + c
$("<td>")
.addClass("tableCell")
.text(cellText)
.data("col", c)
.appendTo(trow);
}
trow.appendTo(tbody);
}
}
In my code, on clicking the cell of table, I get the row and column data div values
$(document).ready(function() {
createDynamicTable($("#tbl"), 10, 5);
$("#tbl td.tableCell")
.click(function() {
alert("Clicked Col=" + $(this).data("col"));
});
});
it is working perfectly
for full code view the site:
http://blogs.microsoft.co.il/blogs/linqed/archive/2009/03/04/generating-html-tables-with-jquery.aspx
I try like this but I cann't getting the table cell data value on stop event. How to get the setted data value in drag and drop.
$(".drag").draggable({
stop: function (ev, ui) {
var pos = $(ui.helper).offset();
var oldData = $("#tbl td.tableCell").data('col');
alert(oldData);
}
});
Help me to get the data value in drag and drop.
Thanks in advance.
Drag and Drop could be restructuring the DOM. Try Using jQuery.live instead of jQuery.click (if supported by your jQuery version) to bind the click event:
$("#tbl td.tableCell")
.live('click', function() {
alert("Clicked Col=" + $(this).data("col"));
});
Since .live() is deprecated you may also want to try the .on() method (if using jQuery 1.7.x).

Making a row editable based on a checkbox in HTML

I have a table in HTML. The contents of this table are dynamically populated. Every row of the table has text boxes and one checkbox. When the page is loaded, all the text boxes in the rows will be in a read-only state.
Now, i want to change the state of the text boxes in a particular row to editable, if the check-box in that row is selected. Also, the text boxes should be made read-only if the check box is de-selected.
How could I accomplish this using Javascript? Please help me.
stating this with plain javascript would be pure pain :)
i suggest using jQuery, eg:
$(':checkbox').click(function() {
var checkbox = $(this);
var row = checkbox.closest('tr');
var inputText = $('input[type=text]', row);
if (checkbox.is(':checked')) {
inputText.attr('readonly', 'readonly');
}
else {
inputText.removeAttr('readonly');
}
});
otherwise
function HandleClickOnCheckbox() {
var checkbox = this;
var row;
var iter = checkbox;
while (!row) {
iter = iter.parent;
if (iter == window) {
break;
}
if (iter.tagName == 'tr') {
row = iter;
break;
}
}
if (!row) {
alert('row not found');
return false;
}
var textBoxes = GetTextBoxes(row);
var method;
if (checkbox.checked) {
var disabledAttribute = document.createAttribute('disabled');
disabledAttribute.nodeValue = 'disabled';
method = function(textBox) {
textBox.setAttributeNode(disabledAttribute);
};
}
else {
method = function(textBox) {
textBox.removeAttribute('disabled', 0);
}
}
for (var i = 0; i < textBoxes.length; i++) {
var textBox = textBoxes[i];
method(textBox);
}
}
function GetTextBoxes(element) {
var textBoxes = new Array();
for (var i = 0; i < element.children.lenght; i++) {
var child = element.children[i];
if (child.tagName == 'input') {
if (child.type == 'text') {
textBoxes.push(child);
}
}
if (child.tagName == 'td') {
var childTextBoxes = GetTextBoxes(child);
if (childTextBoxes.length) {
for (var j = 0; j < childTextBoxes.length; j++) {
var childTextBox = childTextBoxes[j];
textBoxes.push(childTextBox);
}
}
}
}
return textBoxes;
}
this is not tested!
Perhaps, you can start by handling the click event of the checkbox using an if/else statement to check if the checkbox is actually checked. If it is you can use the row within which the checkbox resides to find all the textboxes in the different cells and enable/disable them.
Are you using JQuery or plain Javascript?
If you don't mind using jQuery, you could do:
$('checkbox').click(function() {
if ($(this).attr('checked')) {
$(this).parents('tr').children('input[type="text"]').each().attr('readonly', 'readonly');
} else {
$(this).parents('tr').children('input[type="text"]').each().removeAttr('readonly');
}
})
Or something like that. I'd have to test it to be sure.
Edited to reflect Andreas's comment.
Try this snippet (assumes that the checkbox has a class called "checkbox") if you are using Jquery.
jQuery('tr.checkbox').click(function() {
if (jQuery(this).is(":checked")) {
jQuery('td', this).removeAttr('disabled');
} else {
jQuery('td', this).attr('disabled', '');
}
});`

Categories

Resources