Javascript HTML Table Search - javascript

I have this code to search data in my tables. I'm trying to add a class on the found rows. It works, however once the search input field is empty, it still keeps the class on the cells. Is there any quick way to remove the class once the search field is empty/found is false?
$(document).ready(function() {
$('#search').keyup(function() {
searchTable($(this).val());
});
});
function searchTable(inputVal) {
var table = $('.phonetable');
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() .addClass("searchhighlight");
else $(row).hide();
}
});
}

Check if the value is empty and if it is remove the value:
$('#search').keyup(function() {
var value = $(this).val();
if(value)
searchTable();
else
$('.phonetable tr td').removeClass("searchhighlight");
});
Also look how I traverse the table with $('.phonetable tr td'), you can do something similiar in your current code.

Related

How to make other JQuery run when a separate function runs?

I have the JS code below which filters based on checkboxes being checked or not (I don't think you need to see all the HTML because my question is rather simple/general, I think). All this code works fine, but I added a new function at the bottom (I noted it in the code) that simply has an uncheck all button for one of the sets of checkboxes (because there are like 30 checkboxes and I don't want the user to have to uncheck them all manually).
Anyway, the new script works properly too, except that the overall unrelated script that compares all checkboxes needs to run each time the new Uncheck All/Check All button is clicked.
Is there a simple way to make sure all the other JS runs when this new script is run?
I could be wrong, but I think I just need to somehow trigger this function inside the NEW FUNCTION:
$checkboxes.on('change', function() {
but am not sure how to do that.
ALL JS:
<script>
$(window).load(function(){
Array.prototype.indexOfAny = function(array) {
return this.findIndex(function(v) {
return array.indexOf(v) != -1;
});
}
Array.prototype.containsAny = function(array) {
return this.indexOfAny(array) != -1;
}
function getAllChecked() {
// build a multidimensional array of checked values, organized by type
var values = [];
var $checked = $checkboxes.filter(':checked');
$checked.each(function() {
var $check = $(this);
var type = $check.data('type');
var value = $check.data('value');
if (typeof values[type] !== "object") {
values[type] = [];
}
values[type].push(value);
});
return values;
}
function evaluateReseller($reseller, checkedValues) {
// Evaluate a selected reseller against checked values.
// Determine whether at least one of the reseller's attributes for
// each type is found in the checked values.
var data = $reseller.data();
var found = false;
$.each(data, function(prop, values) {
values = values.split(',').map(function(value) {
return value.trim();
});
found = prop in checkedValues && values.containsAny(checkedValues[prop]);
if (!found) {
return false;
}
});
return found;
}
var $checkboxes = $('[type="checkbox"]');
var $resellers = $('.Row');
$checkboxes.on('change', function() {
// get all checked values.
var checkedValues = getAllChecked();
// compare each resellers attributes to the checked values.
$resellers.each(function(k, reseller) {
var $reseller = $(reseller);
var found = evaluateReseller($reseller, checkedValues);
// if at least one value of each type is checked, show this reseller.
// otherwise, hide it.
if (found) {
$reseller.show();
} else {
$reseller.hide();
}
});
});
//NEW FUNCTION for "UNCHECK ALL" Button
$(function() {
$(document).on('click', '#checkAll', function() {
if ($(this).val() == 'Check All') {
$('input.country').prop('checked', true);
$(this).val('Uncheck All');
} else {
$('input.country').prop('checked', false);
$(this).val('Check All');
}
});
});
});
New button HTML for the new UNCHECK portion:
<input id="checkAll" type="button" value="Uncheck All">
I kept researching and discovered the trigger() function to handle this.
http://api.jquery.com/trigger/

Get input value from each row in JavaScript

function shortDescription(a){
var descriptionInput;
var tbl = $(document.getElementById('21.125-mrss-cont-none-content'));
tbl.find('tr').each(function () {
$(this).find("input[name$='6#if']").keypress(function (e) {
if (e.which == 13) {
descriptionInput = $(this).val();
$(this).val(descriptionInput);
$(document.getElementById('__AGIM0:U:1:4:2:1:1::0:14')).val(descriptionInput);
}
console.log(descriptionInput);
});
});
});
}
This code works perfectly but how do I write this in pure JavaScript? I'm mainly interested in this: How do I perform these tasks without jQuery?
for each row, find the input name that ends in 6#if (the column I want)
on enter, get this input value and add to the console it so I know it's there
input id = "grid#21.125#1,6#if" type="text" value"" name="grid#21.125#1,6#if
oninput = shortDescription(this);
It would be great if you could share a piece of HTML on wich we could try some things, but for the moment, here's what your code looks like written in pure JS :
var descriptionInput;
var tbl = document.getElementById('21.125-mrss-cont-none-content')
Array.from(tbl.getElementsByTagName('tr')).forEach(function(tr) {
Array.from(tr.querySelectorAll("input[name$='6#if']")).forEach(function(input) {
input.onkeypress = function(e) {
if (e.keyCode == 13) {
descriptionInput = input.value;
input.value = descriptionInput; // why ??
document.getElementById('__AGIM0:U:1:4:2:1:1::0:14').value = descriptionInput;
}
console.log(descriptionInput);
}
});
});
If you're not OK with the querySelectorAll, you can use getElementsByTagName, it returns a NodeList that you can turn into an array with the Array.from method and the use filter on the name to find the input with a name containing "6#if".
Best practices ...
Since an ID is unique and the methods getElementsByTageName or getElementsByTagName returns a Live HTMLCollection, it's better if you use these elements as unique variables, so you won't ask your browser to fetch them many times.
Since I don't know what your elements means, I will name the variables with trivial names, here's a better version of the code :
var descriptionInput;
var tbl = document.getElementById('21.125-mrss-cont-none-content');
var tr1 = tbl.getElementsByTagName('tr');
var el1 = document.getElementById('__AGIM0:U:1:4:2:1:1::0:14');
var inputsInTr = Array.from(tr1).map(function(tr) {
return Array.from(tr.getElementsByTagName('input'));
}).reduce(function(pv, cv) {
return pv.concat(cv);
});
var myInputs = inputsInTr.filter(function(input) {
return input.name.indexOf('6#if') != 0;
});
myInputs.forEach(function(input) {
input.onkeypress = function(e) {
if (e.keyCode == 13) {
descriptionInput = input.value;
el1.value = descriptionInput;
}
console.log(descriptionInput);
}
});
I didn't try it, hope it's OK.
Hope it helps,
Best regards,

Javascript/JQuery iterate through table rows and cells and output an attr of checked checkboxes to console

I have the following code, which should go through each table row and dump my array which is declared in an earlier segment of javascript. Then if the checkbox is checked, and it has an attr of "changed=yes" then it should be pushed onto the array and the value should be outputted in console as well as the "path" attribute which should be outputted as a variable that can be overwritten every time the function finds a new checkbox that is checked and changed. So what is wrong with my code? These functions are contained in a function that is called when the user clicks submit on the form.
JsFiddle: http://jsfiddle.net/hU89p/392/
$('#myTable1 tr').each(function(){
myArray = [];
$.each($("input[type='checkbox']:checked").closest("td").siblings("td"),
function () {
if($(this).data("changed") == 'yes'){
myArray.push($(this).attr('checkboxtype'));
filepath = $(this).attr('path');
console.log(myArray);
console.log(filepath);
}
});
});
Here is the Working Fiddle :
Keep it simple :
$('#myTable1 tr').each(function() {
var columns = $(this).find('td');
columns.each(function() {
var box = $(this).find('input:checkbox');
if(box.is(":checked") && box.attr("changed") == 'yes')
{
myArray.push(box.attr('checkboxtype'));
filepath = box.attr('path');
}
});
});
console.log(myArray);
});
You should be using $("input[type='checkbox']:checked").closest("td").siblings("td").each().
See the difference between $().each() and $.each().
try this :-
$('#myTable1 tr').each(function () {
myArray = [];
$(this).find("td input:checkbox").each(function () {
if ($(this).is(":checked") && $(this).attr("changed") == 'yes') {
myArray.push($(this).attr('checkboxtype'));
filepath = $(this).attr('path');
console.log(myArray);
console.log(filepath);
}
});
});

Header is not highlighted in type to filter

I am using a type to filter textbox,where in yser type the data they want to highlight. The data entered in the textbox is then checked against the row in html table.
Row containing the typed data is shown and other rows are hidden.
My problem is that this works as expected but the trouble is that it hides the header.Is there any way that it shows the header along with the highlighted row?
Below is the Script I am using :
function Search() {
var value = $('input[id$="txtSearch"]').val();
if (value) {
$('#table-2 tr:not(:first:hidden)').each(function () {
var index = -1;
//$(this).children('td.hiddencls').each(function () {
$(this).children('td').each(function () {
var text = $(this).text();
if (text.toLowerCase().indexOf(value.toLowerCase()) != -1) {
index = 0;
return false;
}
});
if (index == 0) {
$(this).show();
}
else {
$(this).hide();
}
});
}
else
$('#table-2 tr').show();
}
Kindly provide your valuable suggestions..
Putting this at the end of the Search() definition should work
$('#table-2 tr>th').parent().show();
(I'm assuming the header row has th tags, instead of td)
Otherwise try this
$('#table-2 tr:first').show();

Accessing elements of a table row on the basis of checked radio button

On my webpage, I have a table in which there's a radio button for each row. The name of radio buttons is the same for all rows to access them as a group. I have a button which alerts the row number whose radio button is checked. I'd like to access individual elements of the table of that row as well. Any thoughts as top how I might be able to achieve this would be very welcome.
Here's a Fiddle for the issue:
http://jsfiddle.net/Gz668/13/
On the click of the button "edireq", it currently alerts the row number whose radio button is checked. I'd like to access the values of other fields of the table (requestor, approver, status etc. too.)
Here's the jquery code
$("#edireq")
.button()
.click(function () {
var ele = document.getElementsByName('reqradio');
var len = ele.length;
var flag = -1;
for (var j = 0; j < len; j++) {
if (ele[j].checked) {
flag = j;
}
}
if (flag > -1) {
alert("Row : " + (flag + 1));
} else {
alert("Select a row first");
}
});
Thanks.
You have an odd mix of native javascript and jQuery. You can use the :checked selector to get the chosen radio button, then get the closest tr and read the text of each td within that row. Try this:
$(document).ready(function () {
$('#reqtablenew tr').click(function () {
$('#reqtablenew tr').removeClass("active");
$(this).addClass("active").find('input[name="reqradio"]').prop('checked', true);
});
$("#edireq").button().click(function () {
var $ele = $('input[name="reqradio"]:checked');
if ($ele.length) {
var $tds = $ele.closest('tr').find('td');
var id = $tds.eq(1).text();
var requestor = $tds.eq(2).text();
// and so on..
alert(id);
alert(requestor);
}
else {
alert("Select a row first");
}
});
});
Example fiddle
Try this:
var list = ["Req id","Requestor","Approver","Status","Product","Version","Source","Destination"]; //list of title
if (flag > -1) {
$(".active").find("td:gt(0)").each(function(i){
console.log(list[i]+": "+$(this).text());
});
}
Fiddle here.
I came up with the following:
http://jsfiddle.net/Gz668/16/
$(document).ready(function () {
$("table").on("click", "tr", function(){
$(".active").removeClass("active");
$(this).toggleClass("active");
$(this).find("input[type='radio']").prop("checked", true);
});
$("#edireq").on("click", function(){
activeRow=$(".active");
cells=activeRow.children();
if(cells.length >0){
row={
select:cells[0],
requestId:cells[1],
requestor:cells[2],
approver:cells[3],
status:cells[4],
product:cells[5],
version:cells[5],
source:cells[6],
destination:cells[7]
};
alert(row.requestor.textContent);
}
})
});

Categories