使用jQuery按列而不是行来过滤表

时间:2015-03-24 09:05:23

标签: php jquery html

表格是这样的。我的目标是只显示与搜索框中输入内容相等的区域。

|Stage|Area|Part|
|  A  | 1  | 1  |
|  A  | 1  | 2  |
|  A  | 1  | 3  |
|  A  | 2  | 1  |
|  A  | 2  | 2  |
|  A  | 2  | 3  |
|  A  | 3  | 1  |
|  A  | 3  | 2  |
|  A  | 3  | 3  |

我目前正在关注此code。该网站上还有一个演示版。但如果在搜索框中键入3,则会如下所示:

|Stage|Area|Part|
|  A  | 1  | 3  |
|  A  | 2  | 3  |
|  A  | 3  | 1  |
|  A  | 3  | 2  |
|  A  | 3  | 3  |

我不知道如何按列进行jQuery搜索并给出以下结果:

|Stage|Area|Part|
|  A  | 3  | 1  |
|  A  | 3  | 2  |
|  A  | 3  | 3  |

我是jquery的业余爱好者所以请耐心等待。

表格标记:

<input type="text" id="search"/>

<table width="100%" id="tblData">
    <!-- Cells here -->
</table>

的jQuery

$(document).ready(function()
{
    $('#search').keyup(function()
    {
        searchTable($(this).val());
    });
});

function searchTable(inputVal)
{
    var table = $('#tblData');
    table.find('tr').each(function(index, row)
    {
        var allCells = $(row).find('td');
        if(allCells.length > 0)
        {
            var found = false;
            allCells.each(function(index, td)
            {
                var regExp = new RegExp(inputVal, 'i');
                if(regExp.test($(td).text()))
                {
                    found = true;
                    return false;
                }
            });
            if(found == true)$(row).show();else $(row).hide();
        }
    });
}

1 个答案:

答案 0 :(得分:0)

我曾经写过类似的东西,应该做你需要的东西:

http://codepen.io/chrissp26/pen/vnxdt

上面的示例设置为搜索表格的前两列。这是通过将一列列号作为参数传递来完成的,即第1列将是1:

initLiveFilter(element, [1,2]);

例如,如果您在搜索字段中键入“ hitch ”,它将返回所有搭便车徒步旅行者的书籍。如果您输入“ book ”,它将匹配书籍或有声书籍的所有行。

您的示例


下面的代码段与您的示例更匹配(有一些额外的行可以产生戏剧效果)。在这里,您只能搜索第二列(区域)。

要使这项功能正常工作,只需将表格元素和要编入索引的列传递给initLiveFilter(liveFilter, columnsToIndex);函数调用。

jQuery(document).ready(function(e) {

var columnsToIndex = [2], // first column is 1
	liveFilter = jQuery("#liveFilter");

initLiveFilter(liveFilter, columnsToIndex);
});

// Live Filter
function initLiveFilter(liveFilter, columnsToIndex) {

if (typeof liveFilter !== "undefined" && liveFilter.length > 0) {
	
	liveFilter.wrap('<div class="liveFilter"></div>').parent().prepend('<div class="liveFilterContainer"><div class="group"><input type="text" class="liveFilterInput" value="" placeholder="Filter by Area" /><a href="#" class="clearField" title="Clear Filter">x</a></div></div><div class="noResults"><strong>Sorry.</strong> There is no match for your filter; please try again.</div>');
	
	var	thisObj = this,
		liveFilterWrapper = liveFilter.parent(),
		liveFilterField = liveFilterWrapper.find("input.liveFilterInput"),
		liveFilterGrid = jQuery("#liveFilter"),
		liveFilterGridRows = liveFilterGrid.find("tr:gt(0)"), // gt(0) prevents the first row (normally a TH) from being included.
		liveFilterClear = liveFilterWrapper.find(".clearField"),
		liveFilterNoResults = liveFilterGrid.prev(),
		liveFilterDataArray = [],
	
		//Create an array and populate it with key codes that should not cause shake effects

		characterValidationArray = [8,45,46], //backspace, insert, delete
	
		//Create an array and populate it with key codes that don't trigger an action
	
		characterExclusionArray = [13,20,27,33,34,37,39,35,36,16,17,18,144,145]; // enter, caps, esc, page up, page down, left, right, home, end, shift, ctrl, alt, num lock, scroll lock

	thisObj.init = function(){
		
		if (typeof columnsToIndex !== "undefined" && columnsToIndex.length > 0) {
			
			for (col=0; col<=columnsToIndex.length-1; col++)
			{			
				liveFilterGridRows.children("td:nth-child(" + columnsToIndex[col] + ")").each(function(i){
				
					liveFilterDataArray[liveFilterDataArray.length++] = jQuery(this).text();
				
				});
			}
			
		} else {
			
			liveFilterGridRows.children("td:first-child").each(function(i){
				
				liveFilterDataArray[i] = jQuery(this).text();
				
			});
		}
	
		liveFilterField.on("keyup",function(key){
			
			thisObj.filterRows(key);
			
		});
		
		liveFilterClear.on("click",function(){
	
			thisObj.clearField();
			
			return false;		
		});			
	};
	
	thisObj.clearField = function() {
	
		liveFilterField.val('');
		liveFilterClear.fadeOut(300);
		liveFilterNoResults.slideUp(300);
		liveFilterGridRows.show();
		liveFilterGrid.show();			
	};
	
	thisObj.filterRows = function(key) {
	
		if (jQuery.inArray(key.keyCode,characterExclusionArray) === -1) {
		
			var	liveFilterValue = liveFilterField.val();

			if (liveFilterValue !== "") {

				liveFilterClear.fadeIn(300);

				rowsToShow = [];
				
				var currentRow = 0;
				
			// Check the value entered against a regular expression matched with the column data. If a match exists add the row to a new array

				for (var i=0; i < liveFilterDataArray.length; i+=1) {

					RE = eval("/" + liveFilterValue + "/i");
	
					if (liveFilterDataArray[i].match(RE)) {
						
						rowsToShow.push(currentRow);
						
					}
					
					if(currentRow < liveFilterGridRows.length - 1) {

						currentRow++;
						
					} else {

						currentRow = 0;

					}
				}
			
			// If there are matches, show the grid, hide all the rows and show the selected ones

				if (rowsToShow.length > 0) {

					liveFilterGrid.show();
					liveFilterGridRows.hide();
					
					if (liveFilterNoResults.is(":visible")) {
						liveFilterNoResults.slideUp(150);
					}
					
					for (var i=0; i < rowsToShow.length; i+=1) {

						jQuery(liveFilterGridRows.get(rowsToShow[i])).show();

					}
					
			// If there are NO matches we hide the grid and display an error panel. If an incorrect value is entered while the error panel is visible it shakes itself assuming if it doesn't match any of the excluded values defined in the characterValidationArray
					
				} else {
					
					liveFilterGrid.hide();

					// if the no results panel is shown and the effects queue length is 0 and there are no illegal character presses
											
					if (liveFilterNoResults.is(":visible") && liveFilterNoResults.queue().length === 0 && jQuery.inArray(key.keyCode,characterValidationArray) == -1) {
						
						liveFilterNoResults.effect('shake', {times:3, distance:3}, 100);

					} else {
						liveFilterNoResults.slideDown(150);	
					}
				}
				
			// If the value entered is blank, hide the clear field button, show the grid and all of its rows and hide the no results panel if it is visible
			
			} else {

				thisObj.clearField();
			}
		}		
	};
	
	thisObj.init();
}
}
.liveFilter {
	width: 400px;
	border-radius: 5px;
	-moz-border-radius: 5px;
	background: #fff;
}
.liveFilter .liveFilterContainer {
	border: solid 1px #ccc;
	background: #f5f5f5;
	overflow: hidden;
	padding: 6px;
}
.liveFilter .liveFilterContainer .group {
	position: relative;
	float: left;
}
.liveFilter .liveFilterContainer .liveFilterInput {
	border: solid 1px #ccc;
	padding: 4px 30px 4px 4px;
	color: #666;
	margin: 0;
	outline: 0;
}
.liveFilter .liveFilterContainer .liveFilterInput.default {
	color: #ccc;
	font-style: italic;
}
.liveFilter .liveFilterContainer .clearField {
	background: #80bce8;
	width: 18px;
	padding: 0 6px 3px 6px;
	color: #fff;
	text-decoration: none;
	display: none;
	position: absolute;
	top: 0;
	bottom: 0;
	text-align: center;
	right: -29px;
}
.liveFilter .liveFilterList {
	width: 400px;
	border: solid 1px #ccc;
	border-top: 0;
  border-collapse: collapse;
}
.liveFilter .liveFilterList tr th:first-child,
.liveFilter .liveFilterList tr td:first-child {
	padding-left: 5px;	
}
.liveFilter .liveFilterList tr th {
	text-align: left;
	padding: 3px 0;
}
.liveFilter .liveFilterList tr td {
	border-top: solid 1px #eee;
	padding: 3px 0;
	color: #333;
}
.liveFilter .noResults {
	display: none;
	padding: 10px;
	color: #fff;
	background: #982929;
}


/* For aesthetics only */
				
body {
	margin: 10px;
	font-family: Segoe, "Segoe UI", "DejaVu Sans", "Trebuchet MS", Verdana, sans-serif;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="liveFilter" class="liveFilterList" border="0">
<tbody>
	<tr>
		<th>Stage</th>
		<th>Area</th>
		<th>Part</th>
	</tr>
	<tr>
		<td>A</td>
		<td>1</td>
		<td>1</td>
	</tr>
	<tr>
		<td>A</td>
		<td>1</td>
		<td>2</td>
	</tr>
	<tr>
		<td>A</td>
		<td>1</td>
		<td>3</td>
	</tr>
	<tr>
		<td>A</td>
		<td>1</td>
		<td>4</td>
	</tr>
	<tr>
		<td>A</td>
		<td>1</td>
		<td>5</td>
	</tr>
	<tr>
		<td>A</td>
		<td>2</td>
		<td>1</td>
	</tr>
	<tr>
		<td>A</td>
		<td>2</td>
		<td>2</td>
	</tr>
	<tr>
		<td>A</td>
		<td>2</td>
		<td>3</td>
	</tr>
	<tr>
		<td>A</td>
		<td>2</td>
		<td>4</td>
	</tr>
	<tr>
		<td>A</td>
		<td>2</td>
		<td>5</td>
	</tr>
	<tr>
		<td>A</td>
		<td>3</td>
		<td>1</td>
	</tr>
	<tr>
		<td>A</td>
		<td>3</td>
		<td>2</td>
	</tr>
	<tr>
		<td>A</td>
		<td>3</td>
		<td>3</td>
	</tr>
	<tr>
		<td>A</td>
		<td>3</td>
		<td>4</td>
	</tr>
	<tr>
		<td>A</td>
		<td>3</td>
		<td>5</td>
	</tr>
</tbody>
</table>