Search through Table Cells - javascript

I have a table which is hidden which contains 1272 rows and within it 3 columns with a
Store Name
Postcode
Button
The script is meant to search for all td cells for either a store name or a postcode and is not returning the desired results.
This is a link to the search
Advice appreciated
$("#searchterm").on("keyup", function() {
var value = $.trim($(this).val().toLowerCase());
$("table#participating_stores tr:gt(0)").each(function(index) {
if (index !== 0) {
$row = $(this);
var $tdElement = $row.find("td");
var id = $.trim($tdElement.text().toLowerCase())
var matchedIndex = id.indexOf(value);
if (matchedIndex != 0) {
$row.hide();
}
else {
//highlight matching text, passing element and matched text
$row.show();
}
}
});
});

I think this is what you are looking for. I've made this runnable snippet which hopefully makes things more clear for you and anyone else trying to think about this problem.
$("#searchterm").on("keyup", function() {
var value = $(this).val();
$("table tr:not(:first)").show().filter(function(index) {
return $(this).find("td").text().indexOf(value) == -1;
}).hide();
});
table, tr, td, th{
border: 1px solid black;
padding: 3px;
}
table th{
background-color: #dddddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr><th>Postal Code</th><th>Store Name</th></tr>
<tr><td>12345</td><td>store name</td></tr>
<tr><td>99999</td><td>another store name</td></tr>
<tr><td>54321</td><td>yet another name</td></tr>
<tr><td>34343</td><td>4th name</td></tr>
<tr><td>87898</td><td>fifth name</td></tr>
</table>
<br />
<input type="text" id="searchterm" placeholder="search"></input>

Related

Retrieve table values from an unknown size table

I am in the process of creating a website and I have a HTML table that you can add a row to by clicking a button. There is an input box for every column in every row. When the table is submitted, it should retrieve all the info from all the input boxes and put it in an array that separates the rows.
I am positive that this requires a loop and I tried getting the children from the tbody element, but that didn't return the correct values.
function submitForm() {
var c = $("#tbl").children;
console.log(c);
}
it's very simple, just browse the rows of the array and the cells of each line.
So obviously I do not know what type of array you want, but I've made you here an example of a array with Jquery.
I hope it will help you.
$(function(){
var datas = [];
$.each($('#table tr'), function(index, val) {
var childs = $(this).children('td');
var array = {childs: []};
$.each(childs, function(i, v) {
//get your value
var value = $(this).text();
array.childs.push(value);
});
datas.push(array);
});
//final result
console.log(datas);
});
<!DOCTYPE html>
<html>
<head>
<title>Resultat</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div>
<table id="table" border="1">
<tr>
<td>Value1 line1</td>
<td>Value2 line1</td>
<td>Value3 line1</td>
</tr>
<tr>
<td>Value1 line2</td>
<td>Value2 line2</td>
<td>Value3 line2</td>
</tr>
<tr>
<td>Value1 line3</td>
<td>Value2 line3</td>
<td>Value3 line3</td>
</tr>
</table>
</div>
</body>
</html>
Here is a simplified solution you could easily work into your form submission code.
const tdInputs = document.querySelectorAll('td > input');
let inputValues = [];
tdInputs.forEach(input => inputValues.push(input.value));
console.log(inputValues);
<table>
<tr>
<td><input type="text" value="value1"></td>
</tr>
<tr>
<td><input type="text" value="value2"></td>
</tr>
</table>
http://jsfiddle.net/xpvt214o/1022151/
Assuming...
Since there's hardly any code in the question, I took the liberty to add what I consider necessary to which the question neglected to provide. If you don't have the setup like how my demo is setup, I recommend that you consider refactoring your code a little.
Setup
The demo is fully functional:
Adds and removes rows
A <form> is wrapped around the <table> since there's an <input> in each <td>
The <form> will send its data to a live test server when the submit event is triggered.
The live server will send a response as a JSON which will be displayed in the <iframe> located below the <table>.
This default behavior triggered by asubmit event will be temporarily postponed by this function:
// Earlier in the code, this was called to interrupt the default behavior
event.preventDefault();
...
/* .map() all inputs in the table...
| store all the strings that contain an input's name and value into a jQuery Object
| .get() the data from the jQuery Object as an array
| although optional, you can present it as a string by using `.join()`
*/// Finally, submit the form data to the test server
var dataArray = $('.data input').map(function(idx, txt) {
return `${$(this).attr('name')}: ${$(this).val()}`;
}).get().join(', ');
console.log(JSON.stringify(dataArray));
$('.ui').submit();
/**/
Demo
var count = 0;
var row = `<tr><td><input name='a'></td><td><input name='b'></td><td><input name='c'></td><td><button class='del' type='button'>➖</button></td></tr>`;
$('.ui').on('click', 'button', function(e) {
e.preventDefault();
if ($(this).hasClass('add')) {
count++;
$('.data').append(row);
$('tr:last input').each(function() {
var name = $(this).attr('name');
$(this).attr('name', name+count);
});
} else if ($(this).hasClass('del')) {
$(this).closest('tr').remove();
} else {
var dataArray = $('.data input').map(function(idx, txt) {
return `${$(this).attr('name')}: ${$(this).val()}`;
}).get().join(', ');
console.log(JSON.stringify(dataArray));
$('.ui').submit();
}
});
.ui {width: 100%}
.set {padding: 0;}
.data {width: 100%; table-layout: fixed; border: 1px ridge #777; border-spacing: 1px}
td {width: 30%; padding: 0 1px}
tr td:last-of-type {width: 10%}
.add {margin: 0 0 0 85%;}
iframe {width: 100%}
.as-console-wrapper.as-console-wrapper {
max-height: 20%;
}
.as-console-row.as-console-row::after {
content:'';
padding:0;
margin:0;
border:0;
width:0;
}
<form class='ui' action='https://httpbin.org/post' method='post' target='response'>
<fieldset class='set'>
<button class='add' type='button'>➕</button>
<button>🡺</button>
</fieldset>
<table class='data'>
<tr><td><input name='a0'></td><td><input name='b0'></td><td><input name='c0'></td><td><button class='del' type='button'>➖</button></td></tr>
</table>
</form>
<iframe src='about:blank' name='response'></iframe>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

jQuery search from the begining of input of value in first column

I have a very simple dynamic table search script
What I'm trying to figure out is, how do I make it search from the begining of the value?
eg. I only want it to show the row with the word london in it if one were to search it as lo or lon, currently if you type in on, or ondon it'll return true.
also with this example, how do I force it to only search the first column of each row?
$(document).ready(function() {
$('#search input').keyup(function() {
var text = $(this).val();
if (text != null) {
$('table tbody tr').hide();
$('table tbody tr').filter(':contains("' + text + '")').show();
}
});
});
th {
cursor: pointer;
text-align: left;
}
td {
width: 100px;
}
input[type="text"] {
padding: 10px 5px;
margin: 25px 0;
font-size: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="search">
<input type="text" placeholder="search somethingn" />
</div>
<table id="items">
<thead>
<th>item</th>
<th>something else</th>
</thead>
<tbody>
<tr>
<td>london</td>
<td>test</td>
</tr>
<tr>
<td>new york</td>
<td>test 2</td>
</tr>
</tbody>
</table>
https://jsfiddle.net/8p4w62pe/
There is no built in startsWith selector, but you can write your own:
$.extend($.expr[":"], {
"startsWith": function(elem, i, data, set) {
var text = $.trim($(elem).text()),term = data[3];
return text.indexOf(term) === 0;
},
});
You will also need to change your selector to select the td (not the tr). To only select the first td add :first-child to the selector. Then change the show() to apply to the parent using parent():
$('table tbody tr td:first-child').filter(':startsWith("' + text + '")').parent().show();
Full code:
$(document).ready(function() {
$.extend($.expr[":"], {
"startsWith": function(elem, i, data, set) {
var text = $.trim($(elem).text()),term = data[3];
return text.indexOf(term) === 0;
},
});
$('#search input').keyup(function() {
var text = $(this).val();
if (text != null) {
$('table tbody tr').hide();
$('table tbody tr td:first-child').filter(':startsWith("' + text + '")').parent().show();
}
});
});
Working JS Fiddle
You can loop each of the row, get the first column and then hide the whole row if substring can't be found
$(document).ready(function() {
$('#search input').keyup(function() {
var text = $(this).val();
if (text != null) {
$('table tbody tr').each(function() {
if($(this).find("td:first-child").html().indexOf(text) === -1) {
$(this).hide();
}
});
}
});
});

Case-sensitive Live Search on a Table with jQuery

I have a Live Search on a Table using jQuery. It works really well but is not case sensitive so jim will not show the same as Jim.
Demo: http://jsfiddle.net/qxks62x9/
$("#search").on("keyup", function() {
var value = $(this).val();
$("table tr").each(function(index) {
if (index !== 0) {
$row = $(this);
var id = $.map($row.find('td'), function(element) {
return $(element).text()
}).join(' ');
if (id.indexOf(value) <0) {
$row.hide();
}
else {
$row.show();
}
}
});
});
table, tr, td, th{
border: 1px solid blue;
padding: 2px;
}
table th{
background-color: #999999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><th>Forename</th><th>Surname</th><th>Extension</th></tr>
<tr><td>Jim</td><td>Carey</td><td>1945</td></tr>
<tr><td>Michael</td><td>Johnson</td><td>1946</td></tr>
</table>
<br />
<input type="text" id="search" placeholder=" live search"></input>
You can just lowercase both strings.
Fiddle: https://jsfiddle.net/maq2xmrv/
(id.toLowerCase().indexOf(value.toLowerCase()) < 0)

Remove <tr> if the <td> does not contain the value of the <input>

I'm trying to implement a live search (filtering) feature with jQuery for a table. The table contains a list of people and their grad year and high school. When the user starts typing inside the search input, the table will start filtering out all the rows that do not contain the value of the search input. It will also add the class of highlight to the td that the searched text was in.
How can I filter each row and highlight the td element when the user searches something? I tried implementing this with the code below but to no avail. What can I tweak in this code to get this working correctly?
Below is my code. Here is my jsFiddle: http://jsfiddle.net/mikerodriguez/jybrnt22/2/
jQuery
$("#search").on("keyup", function(){
var input = $(this).val();
$("#search_table tbody tr").each(function(){
var row = $(this);
var td_element = $("#search_table tbody tr td");
if(input !== td_element.text()){
row.hide();
}else{
row.show();
td_element().addClass("highlight");
}
})
});
CSS
body {
margin: 0;
padding: 0;
font-family: Arial;
font-size: 14px;
}
.search_field {
padding: 15px;
}
.search_field input[type="text"] {
padding: 15px;
width: 98%;
font-size: 18px;
}
.search_table_container {
padding: 15px;
}
.search_table {
width: 100%;
}
.search_table th {
background-color: #AAA;
font-weight: bold;
padding: 10px 0px;
}
.search_table td {
text-align: center;
background-color: #CCC;
padding: 15px 0px;
}
HTML
<div class="search_field">
<input type="text" id="search" placeholder="Search for Person, Class, or High School">
</div>
<div class="search_table_container">
<table id="search_table" class="search_table">
<thead>
<tr>
<th>Name</th>
<th>Class</th>
<th>High School</th>
</tr>
</thead>
<tbody>
<tr>
<td>John Smith</td>
<td>2014</td>
<td>Some High School</td>
</tr>
<tr>
<td>Homer Simpson</td>
<td>2015</td>
<td>Springfield High School</td>
</tr>
<tr>
<td>Bugs Bunny</td>
<td>2050</td>
<td>Looney Tunes High School</td>
</tr>
<tr>
<td>George Washington</td>
<td>1749</td>
<td>Georgetown Academy</td>
</tr>
<tr>
<td>Marty McFly</td>
<td>1991</td>
<td>Back to the Future</td>
</tr>
<tr>
<td>Doc Emmet Brown</td>
<td>1965</td>
<td>One Point Twenty-one Gigawatts</td>
</tr>
</tbody>
</table>
</div>
One problem is:
input !== td_element.text()
You're comparing partial input values to the entire contents of your columns. Instead it should be something like
td_element.text().indexOf(input) == -1
But there were actually quite a few issues (including simple syntax errors, e.g., td_element is not a function). I tweaked your example to something that works: http://jsfiddle.net/gh5kjku5/2/
$("#search").on("keyup", function(){
var input = $(this).val();
$("#search_table tbody tr").each(function(){
var row = $(this);
var td_elements = row.find('td');
var colText = td_elements.text();
if(colText.indexOf(input) == -1){
row.hide();
}else{
row.show();
td_elements.addClass("highlight");
}
})});
You'll need to do a bit more work to do things like reset the td background colors when the search box is cleared. Good luck!
hi try this it's working.
$("#search").on("keyup", function () {
var input = $(this).val();
if (input == '') {
$("#search_table tbody tr").show();
} else {
$("#search_table tbody tr").show();
$("#search_table tbody tr").each(function () {
var row = $(this);
var td_element = $("#search_table tbody tr td");
if ($(row).text().trim().toUpperCase().indexOf(input.toUpperCase()) > -1) {
row.hide();
} else {
row.show();
}
});
}
});
see jsfiddle link http://jsfiddle.net/jybrnt22/14/

Sorting and adding inputs like Google - Get directions

I'm trying to do dynamic sortable list with link "Add Destination" such as Google - Get directions screenshot below. Big problem is that in sorted inputs sequence IDs should be maintained and the contents changed after draging. Input is able to drag before "A" and last, remove by "x" right field. Adding additional waypoints, judging by this: directions-waypoints tutorial should be get as array in JavaScript, waypoints is always middle "A" and last fields, input point "A" always name eg. "from", last "goal". I would like to do latter fields filling by autosuggestion from Google places. I was looking everywhere for some solution but its is too different.
EDIT: I collected everything from different sources end I got in result not quite good code: jsfiddle.net/fasE5/5/
Here is a complete working example: http://jsfiddle.net/fasE5/19/
The HTML I came up with:
<div id="sortable" class="isOnlyTwo">
<div class="destination">
<span class="handle">A</span>
<input type="text" name="dest1" value="" />
×
</div>
<div class="destination">
<span class="handle">B</span>
<input type="text" name="dest2" value="" />
×
</div>
</div>
Add Destination
And the CSS, to make it look a little more pretty:
#add_input
{
text-decoration:none;
color:#15C;
margin-left:35px;
}
#add_input:hover
{
text-decoration:underline;
}
.placeholder
{
border:2px dashed #bfbfbf;
margin:5px;
width:240px;
}
.handle
{
background-color:#06B500;
border:2px solid #3D7311;
cursor:n-resize;
padding:0 3px;
border-radius:99px;
font-size:12px;
}
.destination
{
margin:5px 15px;
}
.destination input
{
border:1px solid #B9B9B9;
width:200px;
}
#sortable.isOnlyTwo .remove_input
{
display:none;
}
.remove_input
{
color:#999;
text-decoration:none;
font-weight:bold;
}
.remove_input:hover
{
color:#666;
}
.destination.ui-sortable-helper
{
opacity:0.8;
filter:alpha(opacity=80);
}
.destination.ui-sortable-helper .remove_input
{
display:none;
}
To keep the right order of the input's name attribute and the order letters (A, B, C...), we call to RecalculateOrder on sort update and when removing an destination.
To prevent from removing the last 2 destinations, we add an isOnlyTwo class to the #sortable div when there is only 2 destinaitons left. Which thanks to our CSS hides the remove_input.
For the autocomplete we need GoogleMaps API
<script src="//maps.googleapis.com/maps/api/js?sensor=false&libraries=places" type="text/javascript"></script>
Which provides us an new google.maps.places.Autocomplete(input) to add google's autocomplete functionality.
$(function(){
$("#sortable").sortable({
containment: "document",
placeholder: 'placeholder',
handle: ".handle",
axis: "y",
update: RecalculateOrder,
forcePlaceholderSize: true
});
$("#add_input").click(function () {
var inputIndex = $("#sortable > .destination").length;
// Building the new field's HTML
var html = '<div class="destination">';
html += '<span class="handle">' + String.fromCharCode(inputIndex + 65) + '</span> ';
html += '<input type="text" name="dest' + (inputIndex + 1) + '" value="" /> ';
html += '×';
html += '</div>';
var newField = $(html);
newField .find(".remove_input").click(RemoveInput);
$("#sortable").append(newField ).removeClass("isOnlyTwo");
// Adding autocomplete to the new field
BindAutoComplete(newField.find("input")[0]);
return false;
});
$(".remove_input").click(RemoveInput);
// Adding autocomplete to the first two fields
$("#sortable input").each(function(){
BindAutoComplete(this);
});
function RemoveInput()
{
$(this).parent().remove();
RecalculateOrder();
var isOnlyTwo = $("#sortable > .destination").length == 2;
$("#sortable").toggleClass("isOnlyTwo", isOnlyTwo);
return false;
}
// Recalculating from scratch the fields order
function RecalculateOrder()
{
$("#sortable .handle").text(function(i) {
return String.fromCharCode(i + 65);
});
$("#sortable input").attr("name", function(i){
return "dest" + (i + 1);
});
}
function BindAutoComplete(input)
{
var autocomplete = new google.maps.places.Autocomplete(input);
}
});

Categories

Resources