I need to filter 2 different tables from 1 search/filter input
Now, this code below is working on filtering one table that has the table1 ID
#searchInput is the ID of the text field I'm using
$("#searchInput").keyup(function () {
//split the current value of searchInput
var data = this.value.split(" ");
//create a jquery object of the rows
var jo = $("#table1").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"});
I tried:<br />
$("#table1, #table2").find("tr");<br/>
and:<br />
$("#table1", "table2").find("tr");<br />
but none of them would work!
Related
I want to limit the number of search results from table records to 12 or any number less than 15 etc. This is how far I got with the code. What am i doing wrong?
I tried posting a JS Fiddle in Stack Overflow, but the code is just too long to post.
I prepared a Js Fiddle for better understanding.
Jquery part alone below:
$("#search").on("keyup", function() {
var value = $(this).val();
$("table tr").each(function(index) {
if (index !== 0) {
$row = $(this);
$row.find('td').each (function() {
var id = $(this).text();
if (this.innerHTML.toLowerCase().indexOf(value.toLowerCase()) !== 0) {
$row.slice(0,12).hide();
}
else {
$row.slice(0,12).show();
return false;
}
});
}
});
});
Here is the JSFiddle link which i prepared for better understanding.
https://jsfiddle.net/5g3yxrz4/
You can do it like this: https://jsfiddle.net/5g3yxrz4/5/
$("#search").on("keyup", function() {
var value = $(this).val();
var showRowsLimit = 12;
var rowsShowing = 0;
$("table tr").each(function(index) {
if (index !== 0) {
$row = $(this);
$row.find('td').each (function() {
var id = $(this).text();
if (this.innerHTML.toLowerCase().indexOf(value.toLowerCase()) !== 0 || rowsShowing>=showRowsLimit) {
$row.hide();
}
else {
$row.show();
rowsShowing++;
return false;
}
});
}
});
});
Try this one
const max = 12; // Maximum to show
...
var i = 0;
...
else if(i++ < max) {
...
https://jsfiddle.net/5g3yxrz4/3/
Just added counter for showed "tr"
I am building an application in which I have table with form elements like select, input etc. I want to populate the values selected in form elements to another table.
You can find my code here
JS:
$('button').click(function() {
var rows = $('#table1 tbody tr');
var previewTable = $('#table2 tbody');
previewTable.find('tr').remove();
for (var i = 0; i < rows.length; i++) {
var tr = $('<tr> </tr>');
previewTable.append(tr);
var row_cloned = $(rows[i]).clone();
var cols = rows[i].getElementsByTagName("td");
for (var j = 0; j < cols.length; j++) {
var col_cloned = row_cloned.find('td').clone();
previewTable.find('tr').eq(i).append(col_cloned[j]);
if ($(col_cloned[j]).children().length > 0) {
$(col_cloned[j]).children().each(function(index, item) {
if ($(item).is('select')) {
if ($(item).attr('multiple')) {
var foo = [];
$(item).each(function(i, selected) {
console.log($(selected).val());
foo[i] = $(selected).val();
});
$(col_cloned[j]).text(foo);
} else {
$(col_cloned[j]).text($(item).val());
}
} else if ($(item).is('label')) {
var selected = [];
$(item).find('input:checked').each(function(index, item) {
selected.push($(item).val());
$(col_cloned[j]).append(selected + '<br>');
})
}
})
} else {
$(col_cloned[j]).text($(col_cloned[j]).text());
}
}
}
})
My steps:
Get table1 and table2
Count the number of rows in the table1
Add so many empty rows in the table2
Get each row in table1
Count the td in each row of table1
Find the children in each td
Check if children is select, input, or just plain text
If children is select, determine if it is multi-select or single
Act accordingly for each form elements to copy only values and then append to table2
finish
All this on a button click COPY
Problem: Somehow managed to get the checked input form element values. But failing to get the values selected in select box.
For multi select box my code:
if ($(item).attr('multiple')) {
var foo = [];
$(item).each(function(i, selected) {
console.log($(selected).val());
foo[i] = $(selected).val();
});
$(col_cloned[j]).text(foo);
}
For single select box :
else {
$(col_cloned[j]).text($(item).val());
}
What is my mistake exactly? Thanks in Advance
For selected .val() does not work.You will have to use find() as in reality when you select a select box , its value does not change.
if ($(item).attr('multiple')) {
var foo = [];
$(item).each(function(i, selected) {
foo[i] = $(selected).find(":selected").text(); // see this
});
$(col_cloned[j]).text(foo);
} else {
$(col_cloned[j]).text($(item).find(":selected").text()); // see this
}
For <select> you can't use val().
Using the .val() function on a multi-select list will return an array of the selected values:
This code:
if ($(item).is('select')) {
if ($(item).attr('multiple')) {
var foo = [];
$(item).each(function(i, selected) {
console.log($(selected).val());
foo[i] = $(selected).val();
});
$(col_cloned[j]).text(foo);
} else {
$(col_cloned[j]).text($(item).val());
}
}
Change to this:
if ($(item).is('select')) {
if ($(item).attr('multiple')) {
var foo = $('#multipleSelect').val();
$(col_cloned[j]).text(foo);
} else {
var optionSelected = $(item).find("option:selected");
$(col_cloned[j]).text(optionSelected.val());
}
}
I have this script for searching in table with Highlighting value from "input". But only for first TD in all TR.
Function remove Highlighting
function removeHighlighting(highlightedElements){
highlightedElements.each(function(){
var element = $(this);
element.replaceWith(element.html());
})
}
Function add Highlighting
function addHighlighting(element, textToHighlight){
var text = element.text();
var highlightedText = '<em>' + textToHighlight + '</em>';
var newText = text.replace(textToHighlight, highlightedText);
element.html(newText);
}
Searching in table but only in first TD in TR
$("#search").on("keyup", function() {
var value = $(this).val();
removeHighlighting($("table tr em"));
$("table tr").each(function(index) {
if (index !== 0) {
$row = $(this);
var $tdElement = $row.find('td:first');
var id = $tdElement.text();
var matchedIndex = id.indexOf(value);
if (matchedIndex != 0) {
$row.hide();
}
else {
addHighlighting($tdElement, value);
$row.show();
}
}
});
});
I donĀ“t know how can I searching in all TD and How can I write e.g. some alert if "matchedIndex == -1" (if not found some value from input)
Try looping in all TDs of TR
$("table tr").each(function(index) {
if (index !== 0) {
row = $(this);
$("td", this).each(function(idx) {
var id = $(this).text(); //or $(this).innerText
var matchedIndex = id.indexOf(value);
if (matchedIndex != 0) {
$row.hide();
}
else {
addHighlighting($tdElement, value);
$row.show();
}
}
}
});
A short way
$("table tr > td em").each(function(){
$( this ).replaceWith( $( this ).text() );
});
Adding a span tag with a highlight class is the way to go like suggested in the comments.
Please find a working demo below and in this jsFiddle.
There is a really useful function to remove all the wrapping of the spans. You can do this with $('span.highlight').contents().unwrap().
For finding the text you can use string.search(searchText) or string.match(searchText). The search method will return -1 if nothing is found and the position of the text if found. And match would return occurences in the searchText.
For testing that it finds the first occurence I have added TestY in the table. The flag matched is responsible for this behavior. If you would remove it, it would highlight both TestY elements.
(function () {
var removeHighlight = function () {
$('span.highlight').contents().unwrap();
};
var wrapContent = function (index, $el, text) {
var $highlight = $('<span class="highlight"/>')
.text(text.substring(0, index));
//console.log(text.substring(0, index));
var normalText = document.createTextNode(text.substring(index, text.length));
//console.log(index, $highlight.text(), normalText);
$el.html($highlight).append(normalText);
};
var highlightTextInTable = function ($tableElements, searchText) {
// highlights if text found (during typing)
var matched = false;
//remove spans
removeHighlight();
$.each($tableElements, function (index, item) {
var $el = $(item);
if ($el.text().search(searchText) != -1 && !matched) {
//console.log("matched", $el, $el.html());
wrapContent(searchText.length, $el, $el.html());
//console.log(searchText, $el.text());
if (searchText == $el.text()) {
// found the entry
//console.log("matched");
matched = true;
}
}
});
};
$(function () {
//load table into object
var $tableRows = $('table tr');
var $tableElements = $tableRows.children();
//console.log($tableRows, $tableElements);
$('#search').on('keyup', function (e) {
var searchText = $(this).val();
if (searchText.length == 0) {
// catches false triggers with empty input (e.g. backspace delete or case lock switch would trigger the function)
removeHighlight(); // remove last remaining highlight
return;
}
highlightTextInTable($tableElements, searchText);
});
});
})();
.highlight {
background-color: #00FFFF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="search" />
<table>
<tr>
<td>TestX</td>
<td>Test1.2</td>
<td>Test1.3</td>
<td>Test1.4</td>
</tr>
<tr>
<td>Test2.1</td>
<td>TestY</td>
<td>Test2.3</td>
<td>Test2.4</td>
</tr>
<tr>
<td>Test3.1</td>
<td>TestY</td>
<td>Test3.3</td>
<td>Test3.4</td>
</tr>
</table>
So I have a list of checkboxes in which I push their value to an array which is limited to only 3 selections. These selections get displayed in divs on the page. The push part works fine.. The issue I'm having is when I deselect or uncheck the boxes, I want the values popped or removed from the array which in turn removes or detaches them from the view.
/* checkboxes */
selections = new Array();
$("input[type='checkbox']").change(function () {
var maxAllowed = 3;
var cnt = $("input[type='checkbox']:checked").length;
var checkIt = $("input[type='checkbox']");
var chkboxVal = $(this).val();
//reset selections counter
if (cnt <= maxAllowed) {
$('.selCount .counter').html(selReset-cnt);
selections.push(chkboxVal);
} else if (cnt > maxAllowed) {
$(this).prop("checked", "");
$(this).unbind("click");
$(this).css("cursor","default");
}
var Item1 = selections[0];
var Item2 = selections[1];
var Item3 = selections[2];
var bindedChoice1 = $('<div class="sel1">'+Item1+'</div>');
var bindedChoice2 = $('<div class="sel2">'+Item2+'</div>');
var bindedChoice3 = $('<div class="sel3">'+Item3+'</div>');
//Index of check
if (cnt == 1) {
$(".catSelBar").append(bindedChoice1);
console.log(selections);
}
if (cnt == 2) {
$(".catSelBar").append(bindedChoice2);
console.log(selections);
}
if (cnt == 3) {
$(".catSelBar").append(bindedChoice3);
console.log(selections);
}
if(!$(this).prop("checked") && cnt == 1 && $('.catSelBar div').hasClass("sel1")) {
$(".sel1").detach();
selections.pop();
console.log(selections);
}
if(!$(this).prop("checked") && cnt == 1 && $('.catSelBar div').hasClass("sel2")){
$(".sel2").detach();
selections.pop();
console.log(selections);
}
if(!$(this).prop("checked") && cnt == 2 && $('.catSelBar div').hasClass("sel3")) {
$(".sel3").detach();
selections.pop();
console.log(selections);
}
}); //checkbox change function
When I've done stuff like this in the past, sometimes I'll just rebuild the selections array.
Here is some sample code:
$(function() {
var selections = [],
render_selections = function() {
$('#selections').html(selections.join(', '));
};
$('input[type="checkbox"]').change(function() {
selections = $.map($('input[type="checkbox"]:checked'), function(a) { return a.value; })
render_selections();
});
});
and here is a sample fiddle: http://jsfiddle.net/v4w25pe5/
I have an array of 10 checkboxes. onclick of checkbox i want to get the value of that particular checkbox. That I am able to achieve using my code.When I click in serial order it is working fine. When I click on checkbox 5 after clicking on checkbox 7 the value of checkbox 5 ie..5 is getting added befor 7. I dont want in that order. I want the values to displayed in whatever order I click. My js file is as follows
var selected = new Array();
$(document).ready(function(){
checkBoxTest();
});
function checkBoxTest() {
alert("checkbox test");
for(i = 0; i < 10; i++){
$("#catalog_table").append('<tr><td>Checkbox<input type="checkbox" name ="chkbox" value="' +i+' "/><td></tr>');
test();
}
}
function test() {
$('#catalog_table input:checkbox').change(function() {
var emails = [];
$('#catalog_table input:checkbox:checked').each(function() {
emails.push($(this).val());
});
var textField = document.getElementById("root");
textField.value = emails;
});
}
My HTML code is something like this
<table id="catalog_table"> </table>
<textarea id="root"></textarea>
Can any one please tell me how to do this?
Demo
Its messy, but it works:
http://jsfiddle.net/za7m8/1/
var selected = new Array();
$(document).ready(function(){
$("input[type='checkbox']").on('change', function() {
// check if we are adding, or removing a selected item
if ($(this).is(":checked")) {
selected.push($(this).val());
} else {
for(var i = 0; i<selected.length;i++) {
if (selected[i] == $(this).val()) {
// remove the item from the array
selected.splice(i, 1);
}
}
}
// output selected
var output = "";
for (var o = 0; o<selected.length; o++) {
if (output.length) {
output += ", " + selected[o];
} else {
output += selected[o];
}
}
$("#root").val(output);
});
});
You just have to change your javascript like this.
var selected = new Array();
$(document).ready(function(){
checkBoxTest();
});
function checkBoxTest() {
alert("checkbox test");
for(i = 0; i < 10; i++){
$("#catalog_table").append('<tr><td>Checkbox<input type="checkbox" name ="chkbox" value="' +i+' "/><td></tr>');
test();
}
}
var emails = [];
function test() {
$('#catalog_table input:checkbox').change(function() {
if (this.checked)
{
if ( emails.indexOf( $(this).val() ) === -1 )
{
emails.push($(this).val());
}
} else
{
if ( emails.indexOf( $(this).val() ) !== -1 )
{
var index = emails.indexOf( $(this).val() );
emails.splice(index, 1);
}
}
var textField = document.getElementById("root");
textField.value = emails;
});
}
You need to clear up your code a bit, like this:
I assume that unchecking removes the value from the array, and checking adds.
var selected = new Array(); // What for is this here ?
$(document).ready(function () {
checkBoxTest();
});
function checkBoxTest() {
for (i = 0; i < 10; i++) {
$("#catalog_table").append('<tr><td>Checkbox<input type="checkbox" name ="chkbox" value="' + i + ' "/><td></tr>');
}
test();
}
function test() {
var emails = [],
textField = document.getElementById("root");
$('#catalog_table input:checkbox').change(function () {
var val = $(this).val();
// if you don't want removal of values on `uncheck`, comment out everything below excluding `emails.push(val)` and the last line
if(this.checked){ // if checked
emails.push(val); // add it
}else{
emails.splice(emails.indexOf(val), 1); // remove it if not checked
}
textField.value = emails; // set the value
});
}
DEMO