Search table contents using javascript - javascript

I am currently working on javascript. In this code I have a table and a textbox. When I enter data in the textbox it should show the particular value that I typed but it doesn't search any data from the table. How do I search data in the table?
Here's a jsfiddle http://jsfiddle.net/SuRWn/
HTML:
<table name="tablecheck" class="Data" id="results" >
<thead>
<tr>
<th> </th>
<th> </th>
<th><center> <b>COURSE CODE</b></center></th>
<th><center>COURSE NAME</center></th>
</tr>
</thead>
<tbody>
<tr id="rowUpdate" class="TableHeaderFooter">
<td >
<center> <input type="text" name="input" value="course" ></center>
<center> <input type="text" name="input" value="course1" ></center>
<center> <input type="text" name="input" value="course2" ></center>
</td>
<td>
<center> <input type="text" name="input" value="subject" ></center>
<center> <input type="text" name="input" value="subject1" ></center>
<center> <input type="text" name="input" value="subject2" ></center>
</td>
</tr>
</tbody>
</table >
<form action="#" method="get" onSubmit="return false;">
<label for="q">Search Here:</label><input type="text" size="30" name="q" id="q" value="" onKeyUp="doSearch();" />
</form>
Javascript:
<script type="text/javascript">
//<!--
function doSearch() {
var q = document.getElementById("q");
var v = q.value.toLowerCase();
var rows = document.getElementsByTagName("tr");
var on = 0;
for ( var i = 0; i < rows.length; i++ ) {
var fullname = rows[i].getElementsByTagName("td");
fullname = fullname[0].innerHTML.toLowerCase();
if ( fullname ) {
if ( v.length == 0 || (v.length < 3 && fullname.indexOf(v) == 0) || (v.length >= 3 && fullname.indexOf(v) > -1 ) ) {
rows[i].style.display = "";
on++;
} else {
rows[i].style.display = "none";
}
}
}
}
//-->
</script>

checking with chrome console, it seems that innerHtml for the 'fullname' is returning an error:
var fullname = rows[i].getElementsByTagName("td");
fullname = fullname[0].innerHTML.toLowerCase();
That's because the first tr tag you have is in the thead and it doesn't have any td at all. Changing the start of your loop to 1 will fix that:
for ( var i = 1; i < rows.length; i++ ) { //... and so on

yuvi is correct in his answer. I've incorporated this in a fiddle - http://jsfiddle.net/dBs7d/8/ - that also contains the following changes:
Inputs with course and subject grouped into individual rows.
td tags align underneath th tags.
Code refactored to improve readability.
Instead of checking the html of the td tags I've changed it to check the value attribute of the input tags. This means you can change the value of the input and still search.
I also changed the style alteration to use backgroundColor. This can easily be reverted to display.

See this link.
HTML:
<table name="tablecheck" class="Data" id="results" >
<thead>
<tr>
<th>Course</th>
<th>Subject</th>
<th>COURSE CODE</th>
<th>COURSE NAME</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" value="course" /></td>
<td><input type="text" value="subject" /></td>
</tr>
<tr>
<td><input type="text" value="course1" /></td>
<td><input type="text" value="subject1" /></td>
</tr>
<tr>
<td><input type="text" value="course2" /></td>
<td><input type="text" value="subject2" /></td>
</tr>
</tbody>
</table>
Search here (with jQuery):<input type="text" size="30" value="" onKeyUp="doSearchJQ(this);" /><br />
Search here:<input type="text" size="30" value="" onKeyUp="doSearch(this);" />
Javascript:
function doSearchJQ(input) {
var value = $(input).val();
if (value.length > 0) {
$("#results tbody tr").css("display", "none");
$('#results input[value^="' + value + '"]').parent().parent().css("display", "table-row");
} else {
$("#results tbody tr").css("display", "table-row");
}
}
function doSearch(input){
var value = input.value;
var table = document.getElementById('results');
var tbody = table.querySelector("tbody");
var rows = tbody.querySelectorAll("tr");
var visible, row, tds, j, td, input;
for (var i = 0; i < rows.length; i++) {
visible = false;
row = rows[i];
tds = row.querySelectorAll("td");
for (j = 0; j < tds.length; j++) {
td = tds[j];
input = td.querySelector("input");
console.log(input.value.indexOf(value));
if (input.value.indexOf(value) > -1) {
visible = true;
break;
}
}
if (visible) {
row.style.display = "table-row";
} else {
row.style.display = "none";
}
}
}
With jquery it's more compact function. But you can use clear javascript doSearch.

Why don't you use JQuery DataTables? The plugin has a really nice table view as well as automatically enabled search textbox, and should fit in easily with your JavaScript/PHP solution.
See example table below:
The plugin is well-documented, and widely used. It should be very easy to drop in into an existing application, and style it accordingly.
Hope this helps!

Related

Calculate on change for each row

I have an invoice form to generate a PDF. I want to calculate the inputs after the change of the value that the user fills in the form.
I can calculate the first row, but i want to (1) calculate each row and at the end to (2) calculate all the colums properly. For the first step just to the (1) and i will make the total calculation.
The problem is that i generate the rows with dynamic name and id because i post them in an array to the database. For this example the id is the same for every row of inputs.
PS: i cannot make .change work and i use $(document).on('change', '#qty', function (e) { calculateLine(); }); to trigger the calculation function for each input. I dont know why .change is not working as it support to, with latest jquery.
[invoice.php]
<script>
$(document).ready(function () {
$(document).on('change', '#qty', function (e) { calculateLine(); });
$(document).on('change', '#price', function (e) { calculateLine(); });
$(document).on('change', '#discount', function (e) { calculateLine(); });
$(document).on('change', '#discountPrice', function (e) { calculateLine(); });
});
</script>
[invoice.js]
function calculateLine() {
var qty = parseFloat($('#qty').val());
var price = parseFloat($('#price').val());
var discount = parseFloat($('#discount').val());
var discountPrice = parseFloat($('#discountPrice').val());
var vat = parseFloat($('#vat').val());
var netTotal = 0;
var total = 0;
var vatAmount = 0;
if (!qty && qty == 0) {
return;
}
if (!price && price == 0) {
return;
}
netTotal = qty * price;
if ((!discount || discount == 0) && discountPrice != 0) {
discount = (discountPrice / netTotal) * 100;
}
if ((!discountPrice || discountPrice == 0) && discount != 0) {
discountPrice = (netTotal / 100) * discount;
}
if (discountPrice != 0 && discount != 0) {
discountPrice = (netTotal / 100) * discount;
}
if ((!discount || discount == 0) && (!discountPrice || discountPrice == 0)) {
discountPrice = 0;
discount = 0;
}
total = netTotal - discountPrice;
if (!total || total == 0) {
total = 0;
}
vatAmount = (total / 100) * vat;
$('#total').val(total);
$('#discount').val(discount);
$('#discountPrice').val(discountPrice);
$('#vatAmount').val(vatAmount);
//calculateTotal();
}
[html]
<tr>
<td class="col-xs-0">
<input type="checkbox" name="selected[]" class="checkall">
</td>
<td class="col-xs-5">
<textarea type="text" name="invoice[item][{{j}}][description]" class="form-control description" rows="1" ></textarea>
</td>
<td class="col-xs-1">
<input type="text" name="invoice[item][{{j}}][unit]" class="form-control unit" value="" />
</td>
<td class="col-xs-1">
<input type="text" name="invoice[item][{{j}}][qty]" class="form-control qty" value="" />
</td>
<td class="col-xs-1">
<input type="text" name="invoice[item][{{j}}][price]" class="form-control price" value="" />
</td>
<td class="col-xs-1">
<input type="text" name="invoice[item][{{j}}][discount]" class="form-control discount" value="" >
</td>
<td class="col-xs-1">
<input type="text" name="invoice[item][{{j}}][discountPrice]" class="form-control discountPrice" />
</td>
<td class="col-xs-1">
<input type="text" name="invoice[item][{{j}}][total]" class="form-control total" value="" />
</td>
<td class="col-xs-1">
<input type="text" name="invoice[item][{{j}}][vat]" class="form-control vat" value="{{invcl_vat}}" readonly />
<input type="hidden" name="invoice[item][{{j}}][vatAmount]" class="form-control vatAmount" value="" readonly />
</td>
</tr>
You haven't shown your HTML, but it's clear from your question that you're using the same id (qty, etc.) on more than one element. You can't do that. Every id must be unique on the page. In this case, you'd probably use classes instead.
The general way that you do what you're talking about is indeed to use delegated event handling, then find the containing row, and use that as the starting point looking for descendant inputs using classes rather than ids:
$("selector-for-the-table").on("change", "input", function() {
// Get the row containing the input
var row = $(this).closest("tr");
// Get the values from _this row's_ inputs, using `row.find` to
// look only within this row
var qty = parseFloat(row.find('.qty').val());
var price = parseFloat(row.find('.price').val());
var discount = parseFloat(row.find('.discount').val());
var discountPrice = parseFloat(row.find('.discountPrice').val());
var vat = parseFloat(row.find('.vat').val());
// ...
});
I've also rooted that on the table, rather than document, so it only applies where appropriate.
Live (Simplified) Example:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<table>
<thead>
<tr>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="qty"></td>
<td><input type="text" class="price"></td>
<td><input type="text" class="total" disabled></td>
</tr>
<!-- ...and so on... -->
</tbody>
</table>
<script>
(function() {
"use strict";
$("table").on("change", "input", function() {
var row = $(this).closest("tr");
var qty = parseFloat(row.find(".qty").val());
var price = parseFloat(row.find(".price").val());
var total = qty * price;
row.find(".total").val(isNaN(total) ? "" : total);
});
})();
</script>
</body>
</html>
You've said before that the names are dynamic. Surely there is some characteristic of the fields you're trying to find that is consistent, or you can make them consistent. In the worst case (and I mean in the worst case), you could do something based on position — the first input in the row is row.find("input:eq(0)"), the second is row.find("input:eq(1)"), and so on.
Live Example Using eq:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<table>
<thead>
<tr>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text" disabled></td>
</tr>
<!-- ...and so on... -->
</tbody>
</table>
<script>
(function() {
"use strict";
$("table").on("change", "input", function() {
var row = $(this).closest("tr");
var qty = parseFloat(row.find("input:eq(0)").val());
var price = parseFloat(row.find("input:eq(1)").val());
var total = qty * price;
row.find("input:eq(2)").val(isNaN(total) ? "" : total);
});
})();
</script>
</body>
</html>
But avoid that if you possibly can, it's fragile — if you change the order of columns, you have to change your code.

how to obtain data from dynamic rows created in Javascript into html tag?

There is form which has table containing 1 row and 4 column.The add row button creates a exact row but with different ids .I want to obtain the data filled in this form and send to a php script when clicked on save and continue later button at the bottom .How can I do this?This being a html page.
<form name="myform">
<h3 align="left"><b>Computer</b><h3>
<table id="POITable" border="1" width="100%">
<tr>
<th style="width:10%">Sr No.</th>
<th>Item Description</th>
<th>Quantity</th>
<th>Rate(Inclusive of Taxes)</th>
<th>Total Cost</th>
</tr>
<tr>
<td>1</td>
<td><textarea rows="4" cols="50" id="comp_item"></textarea></td>
<td><input size=25 type="number" id="comp_quant"/></td>
<td><input size=25 type="number" id="comp_rate"/></td>
<td><input size=25 type="number" id="comp_total"/></td>
</tr>
</table>
Total:<input type="text" name="computer" align="right"><br>
<input type="button" id="addmorePOIbutton" value="Add New Row" onclick="insRow()"/>
<script>
function insRow()
{
console.log( 'hi');
var x=document.getElementById('POITable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
new_row.cells[0].innerHTML = len;
var inp1 = new_row.cells[1].getElementsByTagName('textarea')[0];
inp1.id += len;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp3.id += len;
inp3.value = '';
var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
inp4.id += len;
inp4.value = '';
x.appendChild( new_row );
document.getElementsByName("len")[0].value=len;
}
</script>
<input type="submit" value="SAVE AND CONTINUE LATER">
</form>
</html>
To retrive your data in php you must add name attributes to your form input-fields. I have rewritten your code by replacing the input-id's with name instead, like so:
<td><textarea rows="4" cols="50" name="comp_item"></textarea></td>
<td><input size=25 type="number" name="comp_quant"/></td>
<td><input size=25 type="number" name="comp_rate"/></td>
<td><input size=25 type="number" name="comp_total"/></td>
also in your form-element you must specify action and method.
<form name="myform" action="myphpformhandler.php" method="POST">
I took the liberty to rewrite some of your code but the essentials are intact.
<form name="myform" action="myphpformhandler.php" method="POST"> <!-- point action towards the php-file where you wish to handle your data -->
<h3 align="left"><b>Computer</b><h3>
<table id="POITable" border="1" width="100%">
<tr>
<th style="width:10%">Sr No.</th>
<th>Item Description</th>
<th>Quantity</th>
<th>Rate(Inclusive of Taxes)</th>
<th>Total Cost</th>
</tr>
<tr>
<td>1</td>
<td><textarea rows="4" cols="50" name="comp_item"></textarea></td>
<td><input size=25 type="number" name="comp_quant"/></td>
<td><input size=25 type="number" name="comp_rate"/></td>
<td><input size=25 type="number" name="comp_total"/></td>
</tr>
</table>
Total:<input type="text" name="computer" align="right"><br>
<input type="button" id="addmorePOIbutton" value="Add New Row"/>
<input type="submit" value="SAVE AND CONTINUE LATER">
</form>
<script>
(function() { // Prevent vars from leaking to the global scope
var formTable = document.getElementById('POITable');
var newRowBtn = document.getElementById('addmorePOIbutton');
newRowBtn.addEventListener('click', insRow, false); //added eventlistener insetad of inline onclick-attribute.
function insRow() {
var new_row = formTable.rows[1].cloneNode(true),
numTableRows = formTable.rows.length;
// Set the row number in the first cell of the row
new_row.cells[0].innerHTML = numTableRows;
var inp1 = new_row.cells[1].getElementsByTagName('textarea')[0];
inp1.name += numTableRows;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.name += numTableRows;
inp2.value = '';
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp3.name += numTableRows;
inp3.value = '';
var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
inp4.name += numTableRows;
inp4.value = '';
// Append the new row to the table
formTable.appendChild( new_row );
document.getElementsByName("len")[0].value = numTableRows;
}
})();
</script>
Now to access your data in your "myphpformhandler.php" you use the $_POST-variable with your html-element names. like so!
$_POST['comp_item'];
$_POST['comp_item1'];
$_POST['comp_quant'];
$_POST['comp_quant1']; //etc...

Sum of an checkbox list of items

I have a checkbox list of items. I want everytime I check items, to be able to display the price of the item and the sales tax for it, sum a subtotal of each value (price and tax) and sum the total cost. This is what I've done so far (the code is a mix from scripts I' ve found online):
<html>
<head>
<title>List</title>
<SCRIPT>
function UpdateCost() {
var sum = 0;
var gn, elem;
for (i=1; i<3; i++) {
gn = 'item'+i;
elem = document.getElementById(gn);
if (elem.checked == true) { sum += Number(elem.value);
}
}
document.getElementById('totalcost').value = sum.toFixed(2);
}
</SCRIPT>
</head>
<body>
<FORM >
<table border="1px" align="center">
<tr>
<td>List of Items
<td>Price
<td>Tax
</tr>
<tr>
<td><input type="checkbox" id='item1' value="10.00" onclick="UpdateCost()">item1
<td><INPUT TYPE="text" id='price1' SIZE=5 value="">
<td><INPUT TYPE="text" id='tax1' SIZE=5 value="">
</tr>
<tr>
<td><input type="checkbox" id='item2' value="15.00" onclick="UpdateCost()">item2
<td><INPUT TYPE="text" id='price2' SIZE=5 value="">
<td><INPUT TYPE="text" id='tax2' SIZE=5 value="">
</tr>
<TR>
<TD>Subtotals
<TD><INPUT TYPE="text" id="subtotal1" value="" SIZE=5>
<TD><INPUT TYPE="text" id="subtotal2" value="" SIZE=5>
</TR>
<tr>
<td>Total Cost:
<td><input type="text" id="totalcost" value="" SIZE=5>
<td><input type="reset" value="Reset">
</tr>
</table>
</FORM>
</body>
</html>
Here is a working implementation using Knockout.js. The fiddle is here: http://jsfiddle.net/pJ5Z7/.
The ViewModel and Item functions define your data structure and logic. Bindings to properties in the view-model are done in the HTML and Knockout will update those dynamically. These are two-way: I left the price values as inputs to illustrate this. If you check an item and change its price, you will see that change reflected in the rest of the model and view (after the input loses focus).
This approach allows for clean separation of concerns and much more maintainable code. Declarative bindings in Knockout and similar libraries help you avoid manual DOM manipulation as well.
If you want to change your dataset, all you have to do is add or remove items in the initialization code:
var items = [
new Item('item1', 10.00),
new Item('item2', 15.00)
];
With the old approach, you would have had to update the DOM as well as all of your logic. This data could even be loaded dynamically from a web service or anywhere else.
I also cleaned up the markup a bit and moved the size definition of input elements to CSS. It's better practice to define styles there.
If you want to learn more, just go to the Knockout website. There are a number of helpful demonstrations and tutorials.
JavaScript
//Main viewModel
function ViewModel(items) {
var self = this;
self.items = ko.observableArray(items);
self.priceSubtotal = ko.computed(function() {
var i = 0;
var items = self.items();
var sum = 0;
for(i = 0; i < items.length; i++) {
//Only add up selected items
items[i].selected() && (sum += parseFloat(items[i].price()));
}
return sum.toFixed(2);
});
self.taxSubtotal = ko.computed(function() {
var i = 0;
var items = self.items();
var sum = 0;
for(i = 0; i < items.length; i++) {
//Only add up selected items
items[i].selected() && (sum += parseFloat(items[i].taxAmount()));
}
return sum.toFixed(2);
});
self.totalCost = ko.computed(function() {
return (parseFloat(self.priceSubtotal()) + parseFloat(self.taxSubtotal())).toFixed(2);
});
//Functions
self.reset = function() {
var i = 0;
var items = self.items();
var sum = 0;
for(i = 0; i < items.length; i++) {
items[i].selected(false);
}
};
}
//Individual items
function Item(name, price) {
var self = this;
self.name = ko.observable(name);
self.price = ko.observable(price);
self.selected = ko.observable(false);
self.taxRate = ko.observable(0.06);
self.taxAmount = ko.computed(function() {
return (self.price() * self.taxRate()).toFixed(2);
});
}
//Initialization with data- this could come from anywhere
var items = [
new Item('item1', 10.00),
new Item('item2', 15.00)
];
//Apply the bindings
ko.applyBindings(new ViewModel(items));
HTML
<form>
<table border="1px" align="center">
<tr>
<td>List of Items</td>
<td>Price</td>
<td>Tax</td>
</tr>
<!-- ko foreach: items -->
<tr>
<td>
<input type="checkbox" data-bind="checked: selected" />
<span data-bind="text: name"></span>
</td>
<td>
<input type="text" data-bind="value: price"/>
</td>
<td>
<span data-bind="text: selected() ? taxAmount() : ''"></span>
</td>
</tr>
<!-- /ko -->
<tr>
<td>Subtotals</td>
<td>
<span data-bind="text: priceSubtotal"></span>
</td>
<td>
<span data-bind="text: taxSubtotal"></span>
</td>
</tr>
<tr>
<td>Total Cost:</td>
<td>
<span data-bind="text: totalCost"></span>
</td>
<td>
<input type="button" value="Reset" data-bind="click: reset" />
</td>
</tr>
</table>
</form>

Assigning the random password value to a particular column (cells)

I am trying to generate a random password (this code's running perfectly), which will be pasted to the value to the Password text box, but facing a problem while calling the javascript function.
Here is my JavaScript :
function password() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 8;
var randomstring = '';
var table = document.getElementById('table'),
rows = table.getElementsByTagName('tr'),
i,j, cells, password;
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
for (i=0,j = rows.length; i<j;++i)
{
cells = rows[i].getElementsById('td');
if(!cells.length)
{continue;
}
password = cells[j].innerText;
alert("hi "+password);
}
alert("Password is : "+randomstring);
document.f2.password.value = randomstring;
}
Here is my Table :
<table name="table" id="table" cellpadding="4" cellspacing="2" border="1" bgcolor="" >
<tr name="tr" id="tr">
<th><input type="checkbox" name="allCheck" onclick="selectallMe()"></th>
<th>Emp ID</th>
<th>Device</th>
<th>Feature Status</th>
<th>Policy</th>
<th>Password Management</th>
</tr>
<tr>
<% while(rs.next()){ %>
<td><input type="checkbox" name="chkName" onclick="selectall()"></td>
<td><input type="text" name="empId" value="<%= rs.getString(1)%> " disabled="disabled" maxlength="10"></td>
<td><input type="text" name="device" value="<%= rs.getString(2)%>" disabled="disabled" maxlength="10"></td>
<td><input type="text" name="features" value="<%= rs.getString(3)%>" disabled="disabled" maxlength="60"></td>
<td><input type="text" name="policyName" value="<%= rs.getString(4)%>" disabled="disabled" maxlength="10"></td>
<td id="td" name="td"><input type="text" name="password" id="password" value="" ><input type="button" name="Password" value="Password" onclick="password()"><input type="reset" name="Reset" value="Rseset"></td>
</tr>
<% }
%>
</table>
In my JS what is going wrong?? As I want to iterate through Password column, Password() will assign the value to the Password cells.
i would prefer to put this in a comment but i don't have the reputation to yet.
first off is there a specific reason you want the cells to be text input types? Since you are just disabling them on creation.
also look into the rows[index].cells(); and table.rows(); methods in JS. these will give you an array of the cells and rows. from there you can iterate to where you want.
visit to learn more http://www.javascriptkit.com/domref/tableproperties.shtml
hope it helps

dynamically filter rows of a HTML table using JavaScript

So I have this table:
<table border="1" align="center">
<tr>
<td>Broj_pu</td>
<td>Naziv_pu</td>
<td>ID</td>
<td>Naselje</td>
<td>zupanija</td>
</tr>
<tr>
<td><input type="text" ID="broj_pu" onkeydown="Filter(document.getElementById('broj_pu').value, 'broj_pu')" /></td>
<td><input type="text" ID="naziv_pu" onkeydown="Filter(document.getElementById('naziv_pu').value, 'naziv_pu')" /></td>
<td><input type="text" ID="ID" onkeydown="Filter(document.getElementById('ID').value, 'ID')" /></td>
<td><input type="text" ID="naselje" onkeydown="Filter(document.getElementById('naselje').value, 'naselje')" /></td>
<td><input type="text" ID="zupanija" onkeydown="Filter(document.getElementById('zupanija').value, 'zupanija')" /></td>
</tr>
<tr class="row" ID="row_filter">
<td>10000</td>
<td>Zagreb</td>
<td>1</td>
<td>Sljeme</td>
<td>ZAGREBACKA</td>
</tr>
<tr class="row" ID="row_filter">
<td>10000</td>
<td>Zagreb</td>
<td>2</td>
<td>Zagreb-dio</td>
<td>ZAGREBACKA</td>
</tr>
<!-- A lot of rows -->
...
</table>
And also I have started this JavaScript:
<script type="text/javascript">
function Filter(text, column_name){
var x = document.getElementByClassName("row");
var i = 0;
var y;
if (text != ""){
switch (column_name){
case "broj_pu":
for (i = 0; i < x.length; i++){
y = x[i].getElementByTagName("td");
if((y[0].value).match(text) == null){
x[i].attributes(style) = "{display:none;}";
}
}
break;
case "naziv_pu":
y = x[i].getElementByTagName("td");
if((y[1].value).match(text) == null){
x[i].attributes(style) = "{display:none;}";
}
}
break;
case "ID":
y = x[i].getElementByTagName("td");
if((y[2].value).match(text) == null){
x[i].attributes(style) = "{display:none;}";
}
}
break;
case "naselje":
y = x[i].getElementByTagName("td");
if((y[3].value).match(text) == null){
x[i].attributes(style) = "{display:none;}";
}
}
break;
case "zupanija":
y = x[i].getElementByTagName("td");
if((y[4].value).match(text) == null){
x[i].attributes(style) = "{display:none;}";
}
}
break;
}
}
}
</script>
Now, I need to filter the table as the user inputs letters to the text fields, but I have no idea how to edit the display document as I enter the data.
Anyone have an idea?
EDIT1:
So I edited the script but it doesn't seem to work. What did I do wrong?
This question is reminding me of how java script is nasty without any framework support :)
However I have sorted-out this issue for you ( tested on firefox 10.0.2).
check the complete working solution on jsfiddle
please remember this is just working example , you might need to write ALL-Browser compliant script .
script:
var filters=['hide_broj_pu','hide_naziv_pu','hide_ID','hide_naselje','hide_zupanija'];
function ExcludeRows(cls){
var skipRows=[];
for(i=0;i<filters.length;i++)
if(filters[i]!=cls) skipRows.push(filters[i]);
var pattern=skipRows.join('|')
return pattern;
}
function Filter(srcField){
var node=srcField.parentNode;
var index=srcField.parentNode.cellIndex;
//all the DATA rows
var dataRows= document.getElementsByClassName("row");
//ensure that dataRows do not have any filter class added already
var kids= dataRows.length;
var filter ='hide_'+srcField.id;
var pattern = ExcludeRows(filter);
var skipRow = new RegExp(pattern,"gi");
var searchReg =new RegExp('^'+srcField.value,'gi');
var replaceCls= new RegExp(filter,'gi');
for(i=0; i< kids ; i++){
//skip if already filter applied
if(dataRows[i].className.match(skipRow)) continue;
//now we know which column to search
//remove current filter
dataRows[i].className=dataRows[i].className.replace(replaceCls,'');
if(!dataRows[i].cells[index].innerHTML.trim().match(searchReg))
dataRows[i].className=dataRows[i].className +' '+ filter;
}
}
HTML
<table border="1" align="center">
<tr><td>Broj_pu</td><td>Naziv_pu</td><td>ID</td><td>Naselje</td><td>zupanija</td></tr>
<tr>
<td><input type="text" ID="broj_pu" onkeydown="Filter(this)" /></td>
<td><input type="text" ID="naziv_pu" onkeydown="Filter(this)" /></td>
<td><input type="text" ID="ID" onkeydown="Filter(this)" /></td>
<td><input type="text" ID="naselje" onkeydown="Filter(this)" /></td>
<td><input type="text" ID="zupanija" onkeydown="Filter(this)" /></td>
</tr>
<tr class="row" ><td>10000</td><td>Zagreb</td><td>1</td><td>Sljeme</td><td>ZAGREBACKA</td></tr>
<tr class="row" ><td>10000</td><td>Zagreb</td><td>2</td><td>Zagreb-dio</td><td>ZAGREBACKA</td></tr>
</table>
CSS
.hide_broj_pu,
.hide_naziv_pu,
.hide_ID,
.hide_naselje,
.hide_zupanija
{display:none}
For Javascript Table Search, Try:
<p>Search: <input type="text" id="searchTerm" onkeyup="doSearch()" /></p>
<table id="dataTable">
<script>
function doSearch() {
var input, filter, found, table, tr, td, i, j;
input = document.getElementById("searchTerm");
filter = input.value.toUpperCase();
table = document.getElementById("dataTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td");
for (j = 0; j < td.length; j++) {
if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
found = true;
}
}
if (found) {
tr[i].style.display = "";
found = false;
} else {
tr[i].style.display = "none";
}
}
}
</script>

Categories

Resources