JavaScript - saving highlighted rows - javascript

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.

Related

Table Search - adding 'no results' message

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>

jQuery and JavaScript error in Sharepoint 2010

i have downloaded a very nice script for realtime filter for sharepoint list:
https://instantlistfilter.codeplex.com/
i'm adding the code below. and i have two issues with it.
1. it is calling Google service, and i wonder if i can avoid that, since i'm not sure my company will be happy to know this list is going to Google each time someone is filtering it.
2. i'm getting error "Object doesn't support this property or method" for line 106 of the code, which causing the ribbon of the site including the "site action" dropdown button to disappear. I know it is related to the "show" command, but i have no clue how can i fix it.
As said above, i'm using sharepoint 2010. To install this code, i created a text document with it in my documents folder, then created below my list a CEW which is linked to that document. this method worked for me in another page with no issues.
Here is the full code as downloaded from the site above:
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1.2.6");
google.setOnLoadCallback(function() {
$(document).ready(function()
{
jQuery.extend(jQuery.expr[':'], {
containsIgnoreCase: function(a,i,m) {return (a.textContent||a.innerText||jQuery(a).text()||'').toLowerCase().indexOf((m[3]||'').toLowerCase())>=0}
});
$("table.ms-listviewtable tr.ms-viewheadertr").each(function()
{
if($("td.ms-vh-group", this).size() > 0)
{
return;
}
var tdset = "";
var colIndex = 0;
$(this).children("th,td").each(function()
{
if($(this).hasClass("ms-vh-icon"))
{
// attachment
tdset += "<td></td>";
}
else
{
// filterable
tdset += "<td><input type='text' class='vossers-filterfield' filtercolindex='" + colIndex + "' /></td>";
}
colIndex++;
});
var tr = "<tr class='vossers-filterrow'>" + tdset + "</tr>";
$(tr).insertAfter(this);
});
$("input.vossers-filterfield")
.css("border", "1px solid #7f9db9")
.css("width", "100%")
.css("margin", "2px")
.css("padding", "2px")
.keyup(function()
{
var inputClosure = this;
if(window.VossersFilterTimeoutHandle)
{
clearTimeout(window.VossersFilterTimeoutHandle);
}
window.VossersFilterTimeoutHandle = setTimeout(function()
{
var filterValues = new Array();
$("input.vossers-filterfield", $(inputClosure).parents("tr:first")).each(function()
{
if($(this).val() != "")
{
filterValues[$(this).attr("filtercolindex")] = $(this).val();
}
});
$(inputClosure).parents("tr.vossers-filterrow").nextAll("tr").each(function()
{
var mismatch = false;
$(this).children("td").each(function(colIndex)
{
if(mismatch) return;
if(filterValues[colIndex])
{
var val = filterValues[colIndex];
// replace double quote character with 2 instances of itself
val = val.replace(/"/g, String.fromCharCode(34) + String.fromCharCode(34));
if($(this).is(":not(:containsIgnoreCase('" + val + "'))"))
{
mismatch = true;
}
}
});
if(mismatch)
{
$(this).hide();
}
else
{
$(this).show();
}
});
}, 250);
});
});
});
</script>
From what I can see, you're only using the Google code to download jQuery and setup callback when the script gets loaded. To avoid downloading from Google, can't you just load a local copy jQuery?
Download a minimized version of jQuery and upload it to your SharePoint site (Site Assets library or elsewhere).
Then in your code above replace this line
<script src="http://www.google.com/jsapi"></script>
with
<script src="/SiteAssets/{your jquery file name}"></script>
then you can just replace
google.setOnLoadCallback(function() {
$(document).ready(function() {
jQuery.extend(jQuery.expr[':'], {
containsIgnoreCase: function(a,i,m) {return (a.textContent||a.innerText||jQuery(a).text()||'').toLowerCase().indexOf((m[3]||'').toLowerCase())>=0
}
});
});
with
$(function(){
jQuery.extend(jQuery.expr[':'], {
containsIgnoreCase: function(a,i,m) {return (a.textContent||a.innerText||jQuery(a).text()||'').toLowerCase().indexOf((m[3]||'').toLowerCase())>=0
}
});

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>

My signs aren't changing

I am new to JS just playing around to understand how it works.
Why isn't my sign (+,-) changing?
When the div expand it remains with a + sigh never goes to -
Thanks
$(document).ready(function(){
$(".expanderHead").click(function(){
$(this).next(".expanderContent").slideToggle();
if ($(".expanderSign").text() == "+"){
$(".expanderSign").html("−")
}
else {
$(".expanderSign").text("+")
}
});
});
Just guessing at the relationship, since you haven't shown your HTML, but you probably need something like this:
$(document).ready(function () {
$(".expanderHead:visible").click(function () {
var content = $(this).next(".expanderContent");
var sign = $(this).find(".expanderSign");
if (content.is(":visible")) {
content.slideUp();
sign.text("+");
} else {
var expanded = $(".expanderContent:visible");
if (expanded.length > 0) {
expanded.slideUp();
expanded.prev(".expanderHead").find(".expanderSign").text("+");
}
content.slideDown();
sign.text("-");
}
});
});
FIDDLE

How do I get my JavaScript to tile this table properly?

var intervalID;
function autoUpdateFeed()
{
if( document.autoupdatefeedform.autoupdatefeed.checked == true )
{
intervalID = setInterval(updateFeed, 1000);
} else {
clearInterval(intervalID);
}
}
function updateFeed()
{
var oRequest;
try {
oRequest=new XMLHttpRequest();
} catch (e) {
try {
oRequest=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
oRequest=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
oRequest.onreadystatechange=function()
{
if(oRequest.readyState==4)
{
//Start of problem.
var newfeedstable = document.getElementById("newfeeditems");
var newcontent = document.createElement('tr');
newcontent.innerHTML = oRequest.responseText;
while (newcontent.firstChild)
{
newfeedstable.insertBefore(newcontent.firstChild, newfeedstable.firstChild);
}
//End of problem.
}
}
oRequest.open("GET","back/newsfeedlatest.php",true);
oRequest.send(null);
}
Here is the JavaScript code I and my friend are currently using to add new status updates to a table for new status updates on our work-in-process social networking site, the problem is when the new elements are added to the table, they tile to the side, instead of tiling downwards, so I need to know why this is happening and how to fix it, any ideas? For more information, look at the website, you may have to make an account but feel free to use a fake email until we start using email activation again. http://friendgrid.com/
Here's a screenshot of the problem for further reference: http://dl.dropbox.com/u/2281426/Newsfeed%20Error.bmp
The issue would be at the line inside the While:
newfeedstable.insertBefore(newcontent.firstChild, newfeedstable.firstChild);
There the first parameter should be only newcontent without the .firstChild, the firstChild would be inserting only that element and not the newly created <TR>
Altough i suggest you to use DOM methods to modify tables, something easier like:
TableElement.insertRow( 0).innerHTML = oRequest.responseText;
TableElement in your case would be newfeedstable, which if you don't need it later you could reduce to:
document.getElementById("newfeeditems").insertRow( 0).innerHTML = oRequest.responseText;
The 0 as parameter would make the insert always as first row, use a -1 to insert always as last row.
Try next:
oRequest.onreadystatechange=function() {
if(oRequest.readyState===4) {
if(oRequest.status===200) { // HTTP OK
//Start of problem.
var newfeedstable = document.getElementById("newfeeditems");
var newcontent = document.createElement('tr');
newcontent.innerHTML = oRequest.responseText;
// next lines removed: it's a problem: you download a <td> and next code insert its into table directly, without <tr>
//while (newcontent.firstChild)
//{
// newfeedstable.insertBefore(newcontent.firstChild,newfeedstable.firstChild);
//}
// 1) next line added, try next:
newfeedstable.insertBefore(newcontent,newfeedstable.firstChild)
// 2) OR IF RESPONSE CAN CONTAIN MORE THAN ONE <TD> try next (not checked code)
while (newcontent.cells.length) {
var td=newcontent.cells[0];
newcontent.removeChild(td);
var tr=document.createElement('tr');
tr.appendChild(td);
newfeedstable.insertBefore(tr,newfeedstable.firstChild);
}
//End of problem.
}
}
}

Categories

Resources