Calvin Ananda
Calvin Ananda

Reputation: 1530

LocalStorage append New Element

his is : My First JSFiddle. It just appends <li></li>. It works for LocalStorage and shows the result

$(".nav").append($("<li></li>").html(inputan));

I want append like My Second JSFiddle:

var addFolder = '<li>' +
  '<div class="zf-folder">' +
    '<a></a>' +
  '</div>' +
'</li>';

$(".nav").append($(addFolder).html(inputan));

This works for LocalStorage, but is not showing a result when the page is reloaded. I want to use use a method like that because my code looks like this :

With append method $('.nav').append(addFolder);

How can I display LocalStorage result with my second jsFiddle method?

Upvotes: 0

Views: 174

Answers (1)

n4m31ess_c0d3r
n4m31ess_c0d3r

Reputation: 3148

You had addFolder inside your submitButton click handler, hence it is only available in the handler function scope.

$(".submitButton").click(function() {
  var inputan = $("#input_nameFolder").val();

 // move the below variable outside of this function 
  var addFolder = '<li>' +
    '<div class="zf-folder">' +
      '<a></a>' +
    '</div>' +
  '</li>';
  ...
});

Move addFolder outside of the function and it should work.

Updated your fiddle.

Edit: To get correct index

You can add a function that returns the addFolder with the current/updated index. The same function can be used for first time rendering on page load and every time on adding item from the input.

Something like:

var count = 1;
function getNewList() {
  var addFolder = '<li data-index="' + (count++) + '">' +
    '<div class="zf-folder">' +
    '<a></a>' +
    '</div>' +

    '</li>';
  return addFolder;
}

You can check out here: Edited Fiddle for index

// check for the data-index on li items in the console

Upvotes: 2

Related Questions