Jquery cookie holds last value when deleted - json

Please take a look at my website: moskah.nl
If you type something in the field, save and refresh. You wull notice the cookie holds the value. Now if you click on the list it will be deleted. Now try storing multiple list and remove them again. You will see the last clicked list item will not be deleted (on refresh)
I cant figure out why that is. Also I cant give you an example on jsfiddle becuase somehow it doesnt work there. Please look at the source code of website (its very small) to get an idea of what is going on.
This piece is holding the cookie value
$('.fields a').click(function(e) {
var text = $('#inputBox').val();
var values = $.parseJSON($.cookie('myDemoCookie'));
if (!values) {
values = [];
}
values.push(text);
$.cookie('myDemoCookie',JSON.stringify(values),{expires: 7, path: '/' });
$(".jq-text").append('<li>' + text + '</li>');
e.preventDefault();
});
And this is for deleting the list:
$('.jq-text li').live('click', function(e) {
var values = [];
$(".jq-text").find('a').each(function(i, item) {
values.push($(item).text());
});
$.cookie('myDemoCookie', JSON.stringify(values), {
expires: 7
});
$(this).remove();
e.preventDefault();
});

Try this: https://github.com/tantau-horia/jquery-SuperCookie
Set the cookie:
$.super_cookie().create("name_of_the_cookie",{name_field_1:"value1",name_field_2:"value2"});
Insert values:
$.super_cookie().add_value("name_of_the_cookie","name_field_3","value3");
Delete values:
$.super_cookie().remove_value("name_of_the_cookie","name_field_1"));

Related

Is there a better way to get data from localStorage after storing the data without refreshing/reloading the page

I'm trying to make a button that could store the data to the localStorage. After storing the data, I want to get the data without refreshing/reloading the page
The way I use to fix this case is, I put 2 commands on a button. The first command is to store the data, and the second command is to get the data using $scope to make it easy to display it on the page
Here is my code
$scope.storeData = function(){
if(localStorage.getItem('value') === null){
// The value that will set to the localStorage
$scope.data = 'Selamat sore';
// To set the value on $scope.data to localStorage
localStorage.setItem('value', JSON.stringify($scope.data));
//To get the value and display it on the page
$scope.getData = JSON.parse(localStorage.getItem('value'));
}else{
$scope.getData = JSON.parse(localStorage.getItem('value'));
}
}
It's actually working, but maybe there is a better way to do this
Thanks
I find this cleaner, and simpler.
function MyController($scope) {
// if value is null a default 'Selamat sore' is set
$scope.data = localStorage.getItem('value') || 'Selamat sore';
$scope.saveData = function() {
localStorage.setItem('value', JSON.stringify($scope.data));
}
}

How to define a variable that's gonna be retrieved from localstorage (Chrome extension)?

I have a variable defined like this (not sure if it should be with let or var in the first place):
let activated = false;
The first thing that the extension should do is check the value of activated. I think this is the correct syntax:
chrome.storage.local.get(['activated'], function(result) {
activated = result.activated
alert ("activated: " + result.activated)
});
After some logic, I want to change activetedto true, with this syntax:
chrome.storage.local.set({activated: true}, function() {
console.log("activated changed to true: " + activated)
});
However, when I close and open the browser again, activatedis set to false again.
How should I structure this in order to achieve the desired result?
The way to acess a localstorage variable isn't by defining as I was doing in let activated = false;.
The way to add the variable retrieved from localstorage to the program's control flow should be done this way:
chrome.storage.local.get(['activated'], function(result) {
if (result.activated == value) { // Do something }
});

How to open a new tab just after the current tab?

I'm developing a chrome extension and I want to open a new tab, but after the current tab that user is on. This is what I've tried to do:
function clickEvent(info, tab) {
update();
var url= "http://google.com";
var id = tab.id+1;
chrome.tabs.create({'url': url, 'index': id});
}
but the created tab opens at the end of tabs queue in chrome tab bar. After removing 'index': id from chrome.tabs.create, the result is same. I don't know how can I resolve the problem. Can anybody help me?
It sounds like you're creating a 'child' tab, in which case you should set both the index and the openerTabId:
function addChildTab(url, parentTab) {
chrome.tabs.create({
'url': url,
'windowId': parentTab.windowId,
'index': parentTab.index + 1, // n.b. index not id
'openerTabId': parentTab.id // n.b. id not index
});
}
Setting the openerTabId means that the new tab will properly be associated as a child tab of the parent tab, hence:
If you close the child tab while it is active, the parent tab will become the active tab (rather than, say, the tab to the right of the child tab). This makes it behave the same way as links that the user opens in new tabs.
Extensions that show tabs in a tree will work properly.
See also https://code.google.com/p/chromium/issues/detail?id=67539 which added this.
Note: if you're opening the tab in the background (by passing active:false), then parentTab.index + 1 isn't quite right, and instead ideally you'd insert the new tab after existing child (and grandchild) tabs of parentTab:
function addBackgroundChildTab(url, parentTab) {
chrome.tabs.query({'windowId': parentTab.windowId}, function(tabs) {
var parentAndDescendentIds = {};
parentAndDescendentIds[parentTab.id] = true;
var nextIndex = parentTab.index + 1;
while (nextIndex < tabs.length) {
var tab = tabs[nextIndex];
if (tab.openerTabId in parentAndDescendentIds) {
parentAndDescendentIds[tab.id] = true;
nextIndex++;
} else {
break;
}
}
chrome.tabs.create({
'url': url,
'active': false,
'windowId': parentTab.windowId,
'index': nextIndex,
'openerTabId': parentTab.id
});
});
}
But that may be overkill for your purposes, in which case sticking with parentTab.index + 1 as in my first code sample should be fine.
The tab is appended at the end because you're using the wrong argument (id should be index). The tab id is a positive integer which uniquely identifies tabs within a session. Consequently, the value of id is always higher than the number of tabs.
The position of the tab can be read from the index property. So, replace id with index:
function clickEvent(info, tab) {
update();
var url = "http://google.com/";
var index = tab.index + 1;
chrome.tabs.create({'url': url, 'index': index});
}

mvc3 entity framework - convert comma separated list of strings into list<string> in viewmodel, allow users to remove items from list

I am struggling to figure out how to do this with MVC,
I have an entity framework object that has a comma separated list from the db, (can't change the fact that its a horrible csl in the db). I can easily display the list and let them edit it manually. This is rather error prone and would like to split them up and display a list of them in the view. Then allow the user to click a link / button and have them removed from the string and db and the page refreshed to reflect this.
My first thought was to use JQuery to do a ajax json post to do a delete for each item the click an #Html.ActionLink for. I could get it to do the async post back and it would delete the item and would send back a string representing the new string list which I could update the UL with. The second time they clicked a link it would give me a 404, the script I used is:
<script type="text/javascript">
$(document).ready(function () {
$('.viewSeasonsLink').click(function () {
var data =
{
item: $(this).parents('li').first().find('.flagName').text(),
deploymentId: #Model.Id
};
$.post(this.href, data, function (result) {
var list = $("#testme");
list.empty();
var items = result.split(",");
$(items).each(function(index) {
// /* var link = '"' + #Html.ActionLink("Remove", "RemoveItemFromList", "Deployment", null, new { #class = "viewSeasonsLink" }) + '"'; */
var link = '<a class="viewSeasonsLink" href="/SAMSite/Deployment/RemoveItemFromList">Remove</a>';
list.append('<li><span class="flagName">' + items[index] + '</span> - ' + link + ' </li>');
/* list.append('<li><span class="flagName">' + items[index] + '</span> - ' + '\'' + #Html.ActionLink("Remove", "RemoveItemFromList", "Deployment", null, new { #class = "viewSeasonsLink" }) + '\'</li>'); */
});
}, "json");
return false;
});
});
</script>
I could not get the action link to work with the jquery script, so tried hard coding it, still not success.
I then thought I would just try and do a simple actionlink back to a method to remove it and return the normal view, again this posts and will update the db, but will not refresh the webpage at all.
<ul id="testme2">
#foreach (string flag in ViewBag.FeatureFlags)
{
<li><span class="flagName">#flag</span> - #Html.ActionLink("Remove", "RemoveItemFromListTest", "Deployment", null, new { #class = "viewSeasonsLink" })</li>
}
</ul>
public ActionResult RemoveItemFromListTest(string item, int deploymentId)
{
Deployment deployment = db.Deployments.Single(d => d.Id == deploymentId);
ViewBag.CustomerId = new SelectList(db.Customers, "Id", "Name", deployment.CustomerId);
List<string> featureFlags = deployment.FeatureFlags.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
featureFlags.Remove(item);
deployment.FeatureFlags = ConvertBackToCommaList(featureFlags);
ViewBag.FeatureFlags = featureFlags;
//db.SaveChanges();
return View("Edit", deployment);
}
EDIT
released I was being a bit daft at one point:
The second test to get it to do a full post back and do the update was still getting caught by the jquery, (also was not passing in the values). I changed the line to this:
<li><span class="flagName">#flag</span> - #Html.ActionLink("Remove", "RemoveItemFromListTest", "Deployment", new { item = #flag, deploymentId = Model.Id }, null)</li>
which does work, but is a bit naff, it would mean any changes made to the form before the remove link clicked would be lost.
I think I see two issues. One is the initial .Post on the viewSeasonsList click event. You are posting back to the Action that loaded the page, not the Action that will handle the delete. I doesn't seem to me that they would be the same Action base on the approach you described.
var url = '/SAMSite/Deployment/RemoveItemFromList';
then
$.post(url, data, function (result) {
Second, in the Ajax response, when you are rebuilding the list, you are including an href attribute for the links. Why? you are not navigating with those links, you are initiating an Ajax request, which has already been set up.
var link = '<a class="viewSeasonsLink">Remove</a>';
ultimately I had one main problem with the jquery solution. When I added a new LI element it was not being hooked up to the ajax call as this was just happening at document.ready. I now replaced the simple .click with a delegate that will also hook up all elements that are added after the ready event, credit to this page for help with it:
$('#featureflaglist').delegate('.removeflaglink', 'click', RemoveFlagFromList);

GetJSON and using a Show More link

I'm using getJSON to get data from the facebook pages api, and it works just fine, using this code:
$(document).ready(function(){
$.getJSON('url',function(json){
$.each(json.data,function(i,fb){
var output='';
//here I add to output, as this example line:
output += '<div"><a href="http://www.facebook.com/profile.php?id='+fb.from.id+'>'+fb.from.name+'</a>';
$("#results").append(output);
});
});
However, what I'd like to do is similar to what facebook does in it's social plug in where it starts off with 5 entries and has a Show More link, which when clicked, brings in 5 more entries.
Is there a way to do this by altering the code I have?
Thanks
Well, sure there is. Do you want to fetch the other results when a user clicks the "more link" to save bandwidth or is it OK to fetch it at the same time? (async vs sync)
This answer considers the bold text:
output += '<div' + (i >= 5 ? ' style="display: none;"' : '') + '><a href="http://www.facebook.com/profile.php?id=' + fb.from.id +'>'+fb.from.name+'</a></div>';
Oh, and check that line in your code, you had a syntax error and an unmatched div. Also you should have quotation marks around your HTML element's attributes.
For showing the links when the more link is clicked you could do something like:
$('.more').click(function() {
$(this).hide();
// Find the closest ancestor which is a parent of both
// the more link and the actual results list
var $parent = $(this).closest('.parentSelector');
$('.listSelector', $parent).children().show();
return false; // Don't follow the link
});
The parts with the parent stuff above is for the case when you have multiple such results list on the same page and you need to separate them. If you don't need it, here is a simpler variant:
$('.more').click(function() {
$(this).hide();
$('#results').children().show(); // Show all other list items
return false; // Don't follow the link
});