How to convert JQuery to vanilla Javascript - javascript

I'm trying to convert the below JQuery code to a vanilla Javascript version, but got stuck on the loop. This is my current try:
Javascript:
var x = document.getElementById("Table1"), d = x.getElementByTagName("td");
for (let row of x.rows)
{
for(let cell of row.cells)
{
var td_content = $(this).text();
if (td_content != "") {
hide = false;
}
}
}
And below is the original JQuery code I'm trying to convert.
JQuery:
$('#Table1 td').each(function()
{
var td_content = $(this).text();
if (td_content != "") {
hide = false;
}
})

I'd use document.querySelectorAll for easy conversion to vanilla JS.
var hide = true;
var cells = document.querySelectorAll('#Table1 td');
cells.forEach(function(cell) {
if (cell.innerText !== '') {
hide = false;
}
});
console.log(hide);

Related

How to display default message when no results found on Jquery search filter

I'm currently building a page where a search field acts as a filter. It works perfectly fine and shows data against related word, but there is one issue that I'd like to solve. When the entered string or other words is not found in all the existing the page remains blank.
How could I display a default message on my page when no results are found by the filter? Something like a simple <p> explaining that no results were found.
The idea is to display it only once as long as the string is not found.
$('#search_field').on('keyup', function() {
var value = $(this).val();
var patt = new RegExp(value, "i");
$('#userFind').find('tr').each(function() {
var $table = $(this);
if (!($table.find('td').text().search(patt) >= 0)) {
$table.not('.t_head').hide();
}
if (($table.find('td').text().search(patt) >= 0)) {
$(this).show();
}
});
});
This is untested since you haven't provided any table to your question.
After you have looped though all tr, then check if any is visible. If not then append a tr with custom message and remove it and new search.
$('#search_field').on('keyup', function() {
var value = $(this).val();
// console.log(value);
var patt = new RegExp(value, "i");
$(".noRecord").remove();
$('#userFind').find('tr').each(function() {
var $table = $(this);
if (!($table.find('td').text().search(patt) >= 0)) {
$table.not('.t_head').hide();
} else {
$(this).show();
}
});
if ($('#userFind tr:visible').length == 0) {
$('#userFind tbody').append("<tr class='noRecord'><td>No records found.</td></tr>")
}
});
Assuming you have a div:
<div id="zeroHits">no results were found</div>
You can hide/show the #zeroHits div as follows:
$('#search_field').on('keyup', function() {
var value = $(this).val();
var patt = new RegExp(value, "i");
var zeroHits = true;
$('#userFind').find('tr').each(function() {
var $table = $(this);
if (!($table.find('td').text().search(patt) >= 0)) {
$table.not('.t_head').hide();
}
if (($table.find('td').text().search(patt) >= 0)) {
$(this).show();
zeroHits = false;
}
});
if(zeroHits) {
$('#zeroHits').show();
} else {
$('#zeroHits').hide();
}
});
Try this untested code
post your HTML and I can test
const $rows = $('#userFind tbody tr'); // only tbody rows
$('#search_field').on('keyup', function() {
var value = $(this).val();
// console.log(value);
var patt = new RegExp(value, "i");
$rows.each(function() {
const found = $(this).find('td').filter(function() {
return $(this).text().search(patt) != -1
}).length > 0
$(this).toggle(found);
});
$("#notFound").toggle($rows.filter(":visible").length === 0)
});

Javascript PHP How to make a realtime count of table row when change

I have a table that when i type on input field it will show those like data that i searched realtime, i mean it filtered the data when i type in textbox.
i already did the filtered but i want to add some features that shows a text that count how many rows are filtered.
like this
this is my filtering code
function searchTable(inputVal)
{
var table = $('#tblData');
table.find('tr').each(function(index, row)
{
var allCells = $(row).find('td');
if(allCells.length)
{
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();
}
});
}
You can count all / hidden / shown childs using jQuery selectors at the end of your code.
You can use these selectors respectively;
tr,
tr:hidden,
tr:visible
function searchTable(inputVal) {
var table = $('#tblData');
table.find('tr').each(function(index, row) {
var allCells = $(row).find('td');
if (allCells.length) {
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();
}
});
/* Use these values and print / append something to your HTML. */
var allChilds = $('#tblData').find('tr').length;
var shownChilds = $('#tblData').find('tr:visible').length;
var hiddenChilds = $('#tblData').find('tr:hidden').length;
/* Use these values and print / append something to your HTML. */
var countTemplate = "Your template, Total:"+allChilds;
$("#counts").html(countTemplate);
}
Here's modified code of your function:
searchTable = function(inputVal) {
showing = 0;
rows.each(function(index, row) {
var allCells = $(row).find('td');
if (allCells.length) {
var found = false;
allCells.each(function(index, td) {
var regExp = new RegExp(inputVal, 'i');
if (regExp.test($(td).text())) {
showing++;
found = true;
return false;
}
});
if (found == true) $(row).show();
else $(row).hide();
}
$showingSpan.text(showing.toString());
$totalSpan.text(total.toString());
$filteredSpan.text((total - showing).toString());
});
};
And here's working fiddle with implemented functionality of counting filtered and visible rows. You didn't mention what version of jQuery you are using so I assumed the 2.2.4 version.

jQuery / js toLowercase

I can't turn searchBox to a .toLowerCase and my code is case sensitive because of this. I want the code to scan on both upperCase and lowerCase letters.
I wasn't able to find a solution to my problem.
<script>
$("#searchBtn").keyup(function () {
var searchBox = $("#searchBtn").val();
var returnRows = [];
$('tr').not('.headerRow').each(function () {
var addRow = true;
var $currentRow = $(this);
$currentRow.find('td').each(function () {
var $td = $(this);
var word = $td.text();
if (word.indexOf(searchBox) > -1) {
addRow = false;
return false;
// console.log("KOMT IN IF STATEMENT"); //sla deze rij op in een tijdelijke array
}
});
if (addRow) {
returnRows.push($currentRow)
}
});
if (true)
{
$('tr').show();
}
$.each(returnRows, function (i, v) {
$(v).hide();
});
});
</script>
I am not sure but you are making it a bit more complicated. Try something like this:
$("#searchBtn").keyup(function() {
var word = $("#searchBtn").val(),
timer;
if(timer){ clearTimeout(timer); }
timer = setTimeout(function(){
$('tr').not('.headerRow').filter(function(){
var txt = $(this).find('td').text();
return txt.indexOf(word) !== -1 && txt === word;
}).hide();
},900);
});
=== lets you compare strictly. So, in such case T !== t would result in true.

JQuery 1.4.4 and Datatable 1.7 not working

I needed some help with datatables. I might be missing something here:-
Below is my HTML
<div id="cfcPhoneDirectory">
<table id="dynamicPhoneDirectory">
<thead>
<tr><th>Phone Book</th><th>Last Name</th><th>First Name</th><th>Number</th></tr>
</thead>
</table>
And the Script
var rawxmlData = "<PhoneBooks><PhoneBook><name>PhoneBook1</name><type>GLOBAL</type><Contacts><Contact><LNAME>Elis</LNAME><FNAME>Jason</FNAME><Number>1234567890</Number></Contact><Contact><LNAME>Randell</LNAME><FNAME>Mark</FNAME><Number>7895896710</Number></Contact><Contact><LNAME>Flower</LNAME><FNAME>Andy</FNAME><Number>8796024589</Number></Contact></Contacts></PhoneBook><PhoneBook><name>PhoneBook2</name><type>TEAM</type><Contacts><Contact><LNAME>Cullinan</LNAME><FNAME>David</FNAME><Number>6027051573</Number></Contact><Contact><LNAME>Webber</LNAME><FNAME>Mark</FNAME><Number>4842051298</Number></Contact><Contact><LNAME>Mitchell</LNAME><FNAME>Randy</FNAME><Number>7012841562</Number></Contact></Contacts></PhoneBook></PhoneBooks>";
var t = $('#dynamicPhoneDirectory').DataTable();
var xmlData = JSON.stringify(xmlToJson(rawxmlData));
($(xmlData)).find("PhoneBook").each(function ()
{
var phoneBookType = $(this).find("type").text()
$(this).find("Contact").each(function () { t.row.add([phoneBookType, $(this).find("LNAME").text(), $(this).find("FNAME").text(), $(this).find("Number").text()]).draw();
});
});
// Changes XML to JSON
function xmlToJson(xml) {
// Create the return object
var obj = {};
if (xml.nodeType == 1) { // element
// do attributes
if (xml.attributes.length > 0) {
obj["#attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj["#attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType == 3) { // text
obj = xml.nodeValue;
}
// do children
if (xml.hasChildNodes()) {
for(var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName;
if (typeof(obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if (typeof(obj[nodeName].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
}
}
return obj;
};
I am using Jquery version of 1.4.4 and datatable version of 1.7.5?
Any help would be appreciated.
Thanks,
Hash
I gave up debugging the XML parsing - too cryptic. There is no need for porting the XML to JSON at all. So made this up instead :
var table = $('#dynamicPhoneDirectory').dataTable();
var parser = new DOMParser(),
xmlDoc = parser.parseFromString(rawxmlData,"text/xml"),
phoneBook = xmlDoc.querySelector('PhoneBooks'),
phoneBooks = phoneBook.querySelectorAll('PhoneBook');
for (var i=0;i<phoneBooks.length;i++) {
var firstname, lastname, number, contacts,
phoneBookName = phoneBooks[i].querySelector('name').textContent,
phoneBookContacts = phoneBooks[i].querySelector('Contacts'),
contacts = phoneBookContacts.querySelectorAll('Contact');
for (var c=0;c<contacts.length;c++) {
lastName = contacts[c].querySelector('LNAME').textContent;
firstName = contacts[c].querySelector('FNAME').textContent;
number = contacts[c].querySelector('Number').textContent;
//add the contact to dataTables
table.fnAddData([phoneBookName, lastName, firstName, number]);
}
}
this works with datatables 1.7.5 -> http://jsfiddle.net/nsmqg4n2/
the used jQuery is 1.6.4, the lowest possible in jsFiddle, but that does not really inflict on the above code after all. jQuery dataTables 1.7.5 just need jQuery 1.3.x or better.
To retrieve data (for example when the table is clicked) use the API method fnGetData(), example (jQuery 1.6.4, dataTables 1.7.5) :
$("#dynamicPhoneDirectory").delegate('tbody tr', 'click', function() {
var data = table.fnGetData(this);
alert('Number to dial : '+data[3]);
});
forked fiddle -> http://jsfiddle.net/bu87ke7a/
Upgrading my code to use JQuery 1.9.1 and Datatable1.10.7 resolved the issue.

remove array element in jquery

i have an dynamic array of multiple checkboxes. when i checked any checkbox then it get its value and put this in array. i want when i uncheck this then value of this checkbox remove from array. thnku..
$(document).ready(function (e) {
var myCheckboxescolour = new Array();
var myCheckboxesprice = new Array();
var mycolour;
var myprice;
$(".searchcheck").click(function () {
mycolour = '';
myprice = '';
if ($(this).attr('title') == 'colour') {
if (this.checked == true) {
myCheckboxescolour.push($(this).val());
} else {
if (jQuery.inArray($(this).val(), myCheckboxescolour)) {
myCheckboxescolour.pop($(this).val());
}
}
})
};
var removeValue = $(this).val();
myCheckboxescolour = jQuery.grep(myCheckboxescolour, function(value) {
return value != removeValue;
});

Categories

Resources