Table Search - adding 'no results' message - javascript

I am currently using the below table search/filter script in a prototype I am building. User feedback suggests that I need a message when the search returns no matches.
I was wondering if someone could suggest a change that would show a no results message when a user searches for something not found on the table?
The idea is to display it only once as long as the string is not found. Once the search field is refreshed or altered the search/filter would begin again.
NOte: I have seen this same question asked but not with the code base I am using, and I am a user of script but do not fully understand the language, so I cannot apply the suggestions to my code.
Thanks
<script>
$(document).ready(function()
{
$('#search').keyup(function()
{
searchTable($(this).val());
});
});
function searchTable(inputVal)
{
var table = $('#tblData');
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();else $(row).hide();
}
});
}
</script>

You could have a row that shows "no Results", and you can decide whether to show it or not when you find results. So you should store a variable, for example foundResults and at end, check it an decide whether to show it or not.
Something like this:
<script>
$(document).ready(function()
{
$('#search').keyup(function()
{
searchTable($(this).val());
});
});
function searchTable(inputVal)
{
var table = $('#tblData');
var foundResults = false;
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;
foundResults = true;
return false;
}
});
if(found == true)$(row).show();else $(row).hide();
}
});
if (foundResults) {
$(".noresults").hide();
} else {
$(".noresults").show();
}
}
</script>

Related

How to change the text with JS

I am trying to modify this code, so after I create the column, and let's say I want to change the title of it, so I have the edit button, once I click that one, I want to be able to type and change the title of the column.
For the whole code click here.
function Column(name) {
if (name.length > 0) {
var self = this; // useful for nested functions
this.id = randomString();
this.name = name;
this.$element = createColumn();
function createColumn() {
var $column = $("<div>").addClass("column");
var $columnTitle = $("<h3>")
.addClass("column-title")
.text(self.name);
var $columnTitleEdit = $("<button>")
.addClass("btn-edit")
.text("Edit");
var $columnCardList = $("<ul>").addClass("column-card-list");
var $columnDelete = $("<button>")
.addClass("btn-delete")
.text("x");
var $columnAddCard = $("<button>")
.addClass("add-card")
.text("Add a card");
$columnDelete.click(function() {
self.removeColumn();
});
$columnAddCard.click(function(event) {
self.addCard(new Card(prompt("Enter the name of the card")));
});
$columnTitleEdit.click(function(event) { //How to edit this code here so i can rename the title of the Column?
self.editTitle();
});
$column
.append($columnTitle)
.append($columnDelete)
.append($columnAddCard)
.append($columnCardList)
.append($columnTitleEdit);
return $column;
}
} else if (name.length == 0) {
alert("please type something");
$(".create-column").click();
} else {
return;
}
}
Column.prototype = {
addCard: function(card) {
this.$element.children("ul").append(card.$element);
},
removeColumn: function() {
this.$element.remove();
},
editTitle: function() {
if (this.$element == "true") {
this.$element.contentEditable = "false"; //How to edit this code here so i can rename the title of the Column?
} else {
this.$element == "true";
}
}
};
All you have to do is to add an event listener to the edit button. The handler should either replace the title with a textarea, or add the contenteditable attribute to the title element. Here's an example:
// ...
var $columnTitleEdit = $("<button>")
.addClass("btn-edit")
.text("Edit")
.on("click", function(){ //The event listener
if ($(this).hasClass("btn-save")){ //If we're currently editing the title
$columnTitle.attr("contenteditable", false);
$(this).text("Edit").removeClass("btn-save");
} else { //If we're not editing the title
$columnTitle.attr("contenteditable", true).focus();
$(this).text("Save").addClass("btn-save");
}
});

JavaScript - saving highlighted rows

Below is script to highlight rows in html file:
$(function(){
$('table').addClass("table table-bordered table-condensed");
$('.table').on('click', 'tr', function(e){
var $tr = $(this);
var $table = $tr.closest('.table');
var our_index = $($tr,$table).index();
if (e.shiftKey) {
var last_index = $table.data('last-index');
if (last_index) {
if (last_index < our_index) {
while(last_index < our_index) {
$('tbody tr:eq('+(++last_index)+')', $table).click();
}
$('tbody tr:eq('+(last_index)+')', $table).click();
} else {
while(last_index > our_index) {
$('tbody tr:eq('+(--last_index)+')', $table).click();
}
$('tbody tr:eq('+(last_index)+')', $table).click();
}
}
$table.data('last-index',our_index);
} else {
$table.data('last-index',our_index);
}
if ($tr.hasClass('success')) {
$tr.removeClass('success');
} else {
$tr.addClass('success');
}
});
});
I'd like now to save those highlighted rows so that when someone else will open the page, rows highlighted by be will be visible and if I will highlight some cells and then refresh the page they will stay highlighted.
Is there any simple way to achieve that?
Thanks in advance.
-----EDIT-----
I was trying to do it via localStorage:
$('tr').each(function(index){
if(localStorage.getItem(index)!=null){
$(this).addClass(localStorage.getItem(index));
}
});
and part to save:
if ($tr.hasClass('success')) {
$tr.removeClass('success');
} else {
$tr.addClass('success');
$tr.localStorage.setItem(index, 'success');
}
But, that's not working. What I'm doing wrong?
Sorry if my questions are obvious, but I'm starting with web programming.
To condense the comments and try to come up with answers:
You cannot client-side store any information that is available to other users on another computer. You will need some kind of server
When you attempt collaborative editing, you need to handle concurrency or ignore it, so whoever gets to the server first, get their version saved
To communicate with the server, you can use Ajax. NOTE this code was not tested:
var rows = [], saveRows = [];
function saveState() {
$('tbody tr').each() {
if ($(this).is(".success")) rows.push($(this).index())
}
if (rows.join(",") != saveRows.join(",")) {
saveRows = rows.slice(0); // copy;
$.post("storeRows.php",{"rows":rows.length>0?rows.join(","):""},function(res) {
console.log("stored");
if (res.rows.join(",") != saveRows.join(",")) {
$('tbody tr').each(function(i) {
$(this).toggleclass("success",rows.indexOf(i));
});
}
});
}
}
setInterval(saveState,3000);
The server needs to save the list somewhere
1,4,7,9
and then use it to initialise the table when making it OR have the ajax do the job when loading the table.

Using $_GET with Jquery

I currently have the following code on my website:
$(document).ready(function() {
$("#contact").on("click", function(e)
{
e.preventDefault();
$("#contactform").toggle('fast');
});
});
I would like to have an if(isset($_GET['email')); trigger this function as well, so have it open on page load if the $_GET variable is set.
I'm rather new with Jquery and not sure if this is possible, I also have another somewhat related question, I'm not sure if I should make a new question for this as I'm fairly new to stackoverflow as well, but here it is.
Say I have two of these:
$(document).ready(function() {
$("#contact").on("click", function(e)
{
e.preventDefault();
$("#contactform").toggle('fast');
});
});
$(document).ready(function() {
$("#archivestop").on("click", function(e)
{
e.preventDefault();
$("#archives").toggle('fast');
});
});
I want one to close if the other one is opened, how would I go about this?
Thanks!
Here's the Javascript-solution:
function getParam(key) {
var paramsStr = window.location.search.substr(1, window.location.search.length),
paramsArr = paramsStr.split("&"),
items = [];
for (var i = 0; i < paramsArr.length; i++) {
items[paramsArr[i].split("=")[0]] = paramsArr[i].split("=")[1];
}
if (key != "" && key != undefined) {
// return single
if (items[key] != undefined) {
return items[key];
} else {
return null;
}
} else {
// return all (array)
return items;
}
};
if (getParam("email")) {
// ...
}
Regarding your second question you can use the following to determine if an element is visible:
var bool = $('.foo').is(":visible");
So to hide an element if it is visible you would do something like this:
if ($('.foo').is(":visible")) {
$('.foo').hide();
}
I'm silly and have answered my first question. I still have yet to have my coffee.
The following works, just insert it into the div that is to be displayed:
<div id="contactform" style="<?php if(isset($_POST['email'])) echo "display:block;" ?>">
content
</div>

Navigating to Blacklisted URL's and Canceling Them

I need to write a Firefox extension that creates a blacklist and whitelist of URL's, and checks to make sure the user wants to navigate to them whenever the user attempts to do so. I'm doing this using a main script and a content script that I attach to every page (using PageMod); I attached a listener using jQuery to every link (with the tag "a") which executes a function using window.onbeforeunload. I have two questions:
How would I prompt/ask the user if they actually did want to go to the site?
How would I stop the browser from navigating to the site if the user decided not to?
Right now my code passes messages between the two scripts in order to accomplish my goal; as far as I can tell, I can only use "document" in the content script, and save the blacklist/whitelist in the main script. I'm using simple-storage to save my lists, and the port module to pass messages between the scripts.
For question 1, I've attempted using confirm(message) to get a positive/negative response from the user, but the popup either doesn't show up or shows up for a split second then gets automatically answered with a negative response. When I look in my console's error messages, I see a "prompt aborted by user" error.
For question 2, I've already tried using event.preventDefault() by passing the click event to the function (this worked, I think). Is there a better way to do this? I've seen people using window.location = "", et cetera to do this.
Anyways, the code is below:
MAIN.JS
var ss = require("sdk/simple-storage");
exports.main = function() {
if (!ss.storage.blacklist) {
ss.storage.blacklist = [];}
if (!ss.storage.whitelist) {
ss.storage.whitelist = [];}
var data = require("sdk/self").data;
var pageMod = require("sdk/page-mod");
pageMod.PageMod({
include: "*",
contentScriptFile: [data.url("jquery-1.10.2.min.js"),data.url("secChk.js")],
onAttach: function(worker) {
function whiteCNTD(str) {
for (var index = 0; index < ss.storage.whitelist.length; index++) {
if (ss.storage.whitelist[index] == str) {
return index;
}
}
return -1;
}
function blackCNTD(str) {
for (var index = 0; index < ss.storage.blacklist.length; index++) {
if (ss.storage.blacklist[index] == str) {
return index;
}
}
return -1;
}
function checkLists(URL) {
if (whiteCNTD(URL) == -1) {
if (blackCNTD(URL) != -1) {
var bool = false;
worker.port.emit("navq", "Do you want to go to this link and add it to the whitelist?");
worker.port.on("yes", function() {
bool = true;
});
worker.port.on("no", function() {
bool = false;
});
if (bool == true) {
ss.storage.blacklist.splice(index, 1);
ss.storage.whitelist.push(URL);
return true;
}
else {
return false;
}
}
else {
var bool = false;
worker.port.emit("safeq", "Is this a safe site?");
worker.port.on("yes", function() {
bool = true;
});
worker.port.on("no", function() {
bool = false;
});
if (bool == true) {
ss.storage.whitelist.push(URL);
return true;
}
else {
ss.storage.blacklist.push(URL);
return false;
}
}
}
return true;
}
worker.port.on("newURL", function(URL) {
var s = "";
s = URL;
if (checkLists(s)) {
worker.port.emit("good", s);
} else if (!checkLists(s)) {
worker.port.emit("bad", s);
}
});
}
});
}
SECCHK.JS
//Check if the site is a bad site whenever a link is clicked
$("a").click(function(event) {
window.onbeforeunload = function() {
self.port.on("navq", function(message) {
var r = confirm("Do you want to go to this link and add it to the whitelist?");
if (r == true) {
self.port.emit("yes", message);
} else if (r == false) {
self.port.emit("no", message);
}
});
self.port.on("safeq", function(message) {
var r = confirm("Is this a safe site?");
if (r == true) {
self.port.emit("yes", temp);
} else if (r == false) {
self.port.emit("no", temp);
}
});
link = document.activeElement.href;
self.port.emit("newURL", link);
self.port.on("good", function(message) {
return true;
});
self.port.on("bad", function(message) {
return false;
});
}
});

Preserve a value of an element after change using jQuery

For internationalization support, I wrote code that changes the URL from #lang-select dropdown .The code is
$(document).ready(function(){
var sel = document.getElementById('lang-select');
sel.onchange = function(){window.location.replace($('#lang-select').val());};
});
the above code works fine and it changes the URL from http://0.0.0.0:3000/fr to http://0.0.0.0:3000/en.
Now I want to preserve the changed value, but without success. I have written the code below. I don't know why it is wrong/not working .
function langSelect(){
var available_languages = {
"en":"English",
"de":"Deutsch",
"ru" :"Россию",
"fr" : "Française"
};
var languageInUrl= document.URL.split("/")[3];
for(var shortLanguage in available_languages){
if(shortLanguage === languageInUrl) {
var langaugeOptionArray = $("#lang-select>option");
for(var i = 0 ; langaugeOptionArray.length > i ; i++){
if(langaugeOptionArray[i].label === available_languages[shortLanguage]){
langaugeOptionArray[i].selected = true;
return;
}
}
}
}
}
Please tell me what's wrong in above code and since what I am doing is not a new thing, please share what is the best practice to overcome this scenario.
Currently, I am using backend to accomplish this.
$(function() {
$('#lang-select').on("change",function(){
window.location.replace($(this).val());
});
});
function langSelect(){
var available_languages = {
"en":"English",
"de":"Deutsch",
"ru" :"Россию",
"fr" : "Française"
};
var languageInUrl= document.URL.split("/")[3];
var lang = available_languages[languageInUrl];
if (lang) {
var langaugeOptionArray = $("#lang-select>option");
langaugeOptionArray.each(function() {
if($(this).text() === lang){
$("#lang-select").val(lang);
return false;
}
});
}
}
I believe we can even do
if (lang) {
var opt = $("#lang-select").find('option[text="'+lang+'"]').val();
if (opt) $("#lang-select").val(opt);
}
Good luck

Categories

Resources