I want to remove a item in an array but it doesn't get removed. I have the id of the item but I can't use it. Can you show me how I can use the id of item in tasks array?
function appendTaskToList(val, task_id) {
$('#list').append($("<li> <a href='#' class='done-btn'>Done</a>" +
" " + val + " <a href='javascript:void(0)' class='cancel-btn'>Delete</a></li>")
.data("task", task_id));
}
if (localStorage['tasks']) {
var tasks = JSON.parse(localStorage['tasks']);
for(var i=0;i<tasks.length;i++) {
appendTaskToList(tasks[i], i);
}
}else {
var tasks = [];
}
var addTask = function(){
var val = $('#name').val();
tasks.push(val);
var task_id = tasks.indexOf(val);
localStorage["tasks"] = JSON.stringify(tasks);
appendTaskToList(val, task_id);
$('#name').val("").focus();
};
$('#add-btn').click(addTask);
$('#name').keyup(function(e){
if (e.keyCode === 13) {
addTask();
}
});
$(document).delegate('.done-btn', 'click', function() {
$(this).parent('li').addClass('done');
return false;
});
I'm stuck here:
$(document).delegate('.cancel-btn', 'click', function(e) {
var task_elem = $(e.target).closest("li");
console.log(task_elem.data());
var taks_id = task_elem.data();
$(this).parent('li').remove();
localStorage.removeItem(tasks[taks_id]);
});
You only have one localStorage property which is "tasks".
The value of this property is the json you stringify.
In the line localStorage.removeItem(tasks[taks_id]); the value of tasks[taks_id] is not "tasks".
Therefore you are looking to delete something in localStorage that doesn't even exist
What you need to do is remove the item from your tasks javascript array and then save the modified array to localStorage again.
Assuming task_id is the index in array:
//remove from array
tasks.splice(task_id,1);
//store again
localStorage.setItem('tasks',JSON.stringify(tasks));
Related
$(document).ready(function () {
$(":button").click(function () {
var btn = $(":button").val();
if (btn == 'Favoritisieren')
$(":button").css("background-color", "red").prop('value', 'Favoritisiert');
var obj = {"Hed.1" : $("h1")};
var myJSON = JSON.stringify(obj);
localStorage.setItem('myJSON');
else
$(":button").css("background-color","blue").prop('value','Favoritisieren');
});
});
hey, I would like to save the filename and H1 value locally when clicking the button. These should also delete themselves later when the button is pressed again. Does anyone maybe have an idea where my error lies?
Use localStorage.setItem(name, value) to save a named item, var value = localStorage.getItem(name) to read an item, and localStorage.removeItem(name) to delete an item.
Docs: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Your code fixed to save the JSON, and to delete it later.
$(document).ready(function () {
$("button").click(function () {
var btn = $("button").text();
if (btn == 'Favoritisieren') {
$("button").css(({backgroundColor: "red"}).text('Favoritisiert');
var obj = {"Hed.1" : $("h1").text()};
var myJSON = JSON.stringify(obj);
localStorage.setItem('myJSON', myJSON);
} else {
$("button").css({backgroundColor: "blue"}).text('Favoritisieren');
localStorage.removeItem('myJSON');
}
});
});
Assuming we have a button and h1 like this :
<button value="Favoritisieren">click me</button>
<h1>Hello World</h1>
You can do it like this :
$(":button").click(function () {
var btn = $(this).val();
if (btn == 'Favoritisieren') {
$(this).css("background-color", "red").prop('value', 'Favoritisiert');
localStorage.setItem('Hed.1', $("h1").text());
} else {
localStorage.removeItem('Hed.1');
$(this).css("background-color","blue").prop('value','Favoritisieren');
}
});
The syntax to write on localStorage :
localStorage.setItem('myCat', 'Tom');
The syntax for reading the localStorage item is as follows:
const cat = localStorage.getItem('myCat');
The syntax for removing the localStorage item is as follows:
localStorage.removeItem('myCat');
The syntax for removing all the localStorage items is as follows:
localStorage.clear();
my problem after write as object literal as Jquery guide i can't using $(this) to access self on onlick="". please help correct my mistake.
my html
<a
data-id="<?=$product_id?>"
class="compare product-<?=$product_id?>"
onclick="(function(){compareInit.comGet();})()"
></a>
my js
var compareInit = {
/* Store Item Compare */
comGet: function() {
var e = $(this);
var item_id = e.data('id');
var item_image = e.find(".compare-hidden-image").val();
var item_name = e.find(".compare-hidden-name").val();
var count_item = $(".compare-item").length;
var item_dialog = $(".compare-tray-dialog");
var compare_button = $(".compare-tray-item");
item_dialog.show();
if (count_item > 1) {
} else {
$(".product-"+ item_id).css("color", "red").attr('onclick','');
}
if (count_item === 0) {
compare_button.removeClass('activate').addClass('deactivate');
} else {
compare_button.removeClass('deactivate').addClass('activate');
}
$('.compare-remove').on("click", function() {
var rem_id = $(this).data('id');
$("." + rem_id).remove();
$(".product-" + rem_id).css("color", "#fff").attr('onclick','(function(){compareInit.comGet();})()');
compare_button.removeClass('activate').addClass('deactivate');
});
}
};
Thank in advance.
You can pass the this identifier from the onclick event and then access it under a name other than this such as elem as a parameter of your function.
var compareInit = {
/* Store Item Compare */
comGet: function(elem) {
console.log("working");
var e = $(elem);
var item_id = e.data('id');
var item_image = e.find(".compare-hidden-image").val();
var item_name = e.find(".compare-hidden-name").val();
var count_item = $(".compare-item").length;
var item_dialog = $(".compare-tray-dialog");
var compare_button = $(".compare-tray-item");
item_dialog.show();
if (count_item > 1) {} else {
$(".product-" + item_id).css("color", "red").attr('onclick', '');
}
if (count_item === 0) {
compare_button.removeClass('activate').addClass('deactivate');
} else {
compare_button.removeClass('deactivate').addClass('activate');
}
$('.compare-remove').on("click", function() {
var rem_id = $(this).data('id');
$("." + rem_id).remove();
$(".product-" + rem_id).css("color", "#fff").attr('onclick', '(function(){compareInit.comGet();})()');
compare_button.removeClass('activate').addClass('deactivate');
});
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a data-id="3636" class="compare product-3636" onclick="compareInit.comGet(this)">Testing</a>
You need to pass-on the your required DOM element's this reference as follows:
onclick="(function(){compareInit.comGet();})()"; here you are invoking an anonymous function without passing anything to it. So there inside it this reference means that anonymous function itself. To achieve your goal you need to pass DOM reference as follows:
var compareInit = {
/* Store Item Compare */
comGet: function(thisRef) {
alert($(thisRef).text());
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="mydiv" onclick="(function(thisRef){compareInit.comGet(thisRef);})(this)">Click Me!</div>
Try this: apply the this inside the onclick function .If you apply this in object function its get the data from that object only
var compareInit ={
comGet : function(that){
console.log(that.innerHTML)
}
}
<a onclick="compareInit.comGet(this)">hello</a>
Alternate:
If get the this from whole object try with return like below .its like a jquery object $(element).html()
var compareInit = function(that){
return {
comGet : function(){
console.log(that.innerHTML)
}
}
}
<a onclick="compareInit(this).comGet()">hello</a>
Hi trying to update the local JSON file with new input values.
Creating a posts app which is now working on local Json file.
I have a button and a text area, and a dynamic list.
once I add some input values in textarea and submit it should get appends to li and if I add another value then it should get append to another li.
What ever new values had added it should get append to the local json file.
Here is the code what I have tried.
HTML:
<ul class='Jsonlist'></ul>
<a id='postData' href='#'>Post</a>
<textarea id="tArea"></textarea>
JS:
var Json = {"three":["red","yellow","orange"]}
var items = [];
$.each( Json, function( key, val ) {
debugger;
items.push( "<li id='" + key + "'>" + Json.three + "</li>" );
});
$('.Jsonlist').append(items);
$('#postData').click(function(){
a=$('#tArea').val();
$(".Jsonlist li").append(a);
});
Working Demo
JS fiddle:
http://jsfiddle.net/JwCm9/
What's inside?
variable to hold the items
var items;
creates <ul> for items and for each item a <li>
function make_list() {
var list = $(".Jsonlist");
list.empty();
for (var i in items) {
var value = items[i];
var li = $('<li>');
li.html(value);
list.append(li);
}
};
saving and reading from local json from/into items
function save_to_local_json() {
var items_json = JSON.stringify(items);
localStorage.setItem('items', items_json);
};
function read_from_local_json() {
var items_json = localStorage.getItem('items');
items = JSON.parse(items_json);
// If the file is empty
if (!items) {
items = [];
}
};
first time calling to these functions:
read_from_local_json();
make_list();
on click event
$('#postData').click(function () {
var text = $('#tArea').val();
items.push(text);
make_list();
save_to_local_json();
});
updated my answer:
function update_json(json_data){
localStorage.setItem('json',JSON.stringify(json_data));
}
function fetch_json(){
var json_data_local = JSON.parse(localStorage.getItem('json'));
return json_data_local;
}
function display_list(json_data){
json_data.three.forEach(function(val,key) {
$('.Jsonlist').append("<li id='" + key + "'>" + val + "</li>");
});
}
console.log(localStorage.getItem('json'));
if(localStorage.getItem('json') == ""){
var Json = {"three":["red","yellow","orange"]}
update_json(Json);
}
var Json = fetch_json();
display_list(Json);
console.log(Json);
$('#postData').click(function(){
a=$('#tArea').val();
Json.three.push(a);
update_json(Json);
$('.Jsonlist li').remove();
display_list(fetch_json());
});
How do we stor selected row in array in JavaScript?
You shoud be more specific in what kind of object youre using in your html (DOM) code.
exampl:
if you're using a SELECT 'resources' in a form
var fl = form.resources.length -1;
//Pull selected resources and add them to list
for (fl; fl > -1; fl--) {
if (form.resources.options[fl].selected) {
theText = form.resources.options[fl].text;
theValue = form.resources.options[fl].value);
//your code to store in an aray goes here
//...
}
}
If I got it you want to store selected table rows using javaScript.
If yes, this may help.
This piece of code is to accumulate selected ID's (dataId), based on selection of selected row's id(elemId), in an input (hidId).
I have modified my original code to maintain the records in an Array as well.
function checkSelection(hidId,elemId,dataId)
{
var arr =
str = '_' + dataId + '_';
hid = document.getElementById(hidId);
row = document.getElementById(elemId);
if(!row.classList.contains("selected")) {
row.classList.add("selected");
if(!hid.value.toString().includes(str)) {
hid.value = hid.value + str;
}
if(arr.includes(dataId))
arr.push(dataId);
}
else {
row.classList.remove("selected");
if(hid.value.toString().includes(str))
hid.value = hid.value.replace(str,"");
if(!arr.indexOf(dataId)==-1)
delete arr[arr.indexOf(dataId)];
}
alert(arr.toString());
}[I have tested it][1]
to focus more on the Array() a basic solution would be as below:
function checkSelect(hidId,elemId,dataId)
{
row = document.getElementById(elemId);
str = "";
if(document.getElementById(hidId).getAttribute("value")!=null)
str = str+document.getElementById(hidId).getAttribute("value");
str= str.replace('[','')
.replace(']','')
.replace('"','')
.replace('\\','');
document.getElementById(hidId).setAttribute("value",str);
alert(document.getElementById(hidId).value);
var arr = new Array();
if(document.getElementById(hidId).value.length!=0 ) {
arr=document.getElementById(hidId).value.split(',');
}
if(!row.classList.contains("selected")) {
row.classList.add("selected");
if(!arr.includes(dataId.toString())) {
arr.push(dataId.toString());
}
}
else {
row.classList.remove("selected");
if(arr.includes(dataId.toString()))
{
delete dataId.toString();
arr.splice(arr.indexOf(dataId.toString()),1)
}
}
if(arr.length>0) {
document.getElementById(hidId).setAttribute("value", arr.toString());
}
else
document.getElementById(hidId).setAttribute("value", "");
}
I have this code and I keep getting undefined if I test the selectedIndex.
alert(x.selectedIndex);
So, setting it is also a problem.
Does anyone possibly see what the problem is?
//makes list off tags
function ttyps_select(data,naamsel,selectid, containerid){
if(!ttyps.length){
jQuery.each(data, function(index, itemData) {
ttyps.push( new Tagtype(itemData.tag_id, itemData.tag ));
});
}
opties = "<option value=\"-1\"></option>\n";
for(var i=0; i<ttyps.length; i++) {
var dfnkey = ttyps[i].tag_id;
var dfnsel = ttyps[i].tag;
if (dfnkey==selectid) {
opties +="<option value="+ttyps[i].tag_id+" SELECTED>"+dfnsel+"</option>\n";
} else {
opties +="<option value="+dfnkey+">"+dfnsel+"</option>\n";
}
}
$("<select name=\"" + naamsel + "\" size=\"1\" ></select>")
.html(opties)
.change(function(e){
select_tag(containerid);
})
.appendTo("#"+naamsel);
}
function select_tag(id) {
var x = $('#frmttypid'+id+' select');
var ttidx = x.val();
var tag = getTagtype(ttidx).tag;
x.selectedIndex=0;
x.blur();
if( tag ){
document.forms['frmtags']['frmtag'+id].value=tag;
}
}
thanks, Richard
$('selector') (jQuery) returns an object with array-like collection of matched DOM nodes. Your x variable is an jQuery object, not a reference to any particular <select/> element. use
x[0].selectedIndex
x[0] is a reference to the first DOM node in the jQuery object.