Skip to content
Advertisement

Jquery – Add tags in html with localStorage array value?

This code does not work!!

All the code is correct, only the a tag is not added. Why?

I want the values ​​to be displayed after refreshing the page

$('#Search_Id').keypress(function(event) {
  var keycode = (event.keyCode ? event.keyCode : event.which);
  if (keycode == '13') {
    let key = "Search_Text";
    let value = $(this).val();

    if (key && value) {
      if (localStorage.getItem(key)) {
        let vals = localStorage.getItem(key).split(',');
        if (!vals.includes(value)) {
          vals.push(value);
          vals.sort();
          localStorage.setItem(key, vals.join(','));
        }
        for (var i = 0; i <= vals.length - 1; i++) {
          let txt = vals[i];
          $(".search-header .search-result ul.search-result-list li#story_search").append('<a name="search_txt" class="txt-search-story" href="#"><span>' + txt + '</span></a>');
        }
      } else {
        localStorage.setItem(key, value);
      }
      location.reload();
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li id="story_search" class="span-row"></li>
</ul>

Advertisement

Answer

Consider the following example.

Fiddle: https://jsfiddle.net/Twisty/L876vjmc/46/

HTML

<form id="searchForm">
  Search: <input id="searchTerm" type="text">
</form>
<ul>
  <li id="searchStory" class="span-row"></li>
</ul>
<button id="clearStory">Clear</button>

JavaScript

$(function() {
  function getItems(key) {
    console.log("Getting Items from key: " + key);
    var results = [];
    try {
      results = localStorage.getItem(key).split(',');
    } catch (error) {
      console.log(error);
    }
    console.log(results);
    return results;
  }

  function setItems(key, data) {
    console.log("Setting Items into key: " + key);
    try {
      localStorage.setItem(key, data.join(','));
      return true;
    } catch (error) {
      console.log(error);
      return false;
    }
  }

  function resetItems(key) {
    localStorage.removeItem(key);
    $("#searchStory").empty();
  }

  function searchItems(key, term) {
    console.log("Search: " + key + ", for: " + term);
    var items = getItems(key);
    if (items.indexOf(term) == -1) {
      console.log("Not Found. Pushing it.");
      items.push(term);
    }
    items.sort();
    console.log(items);
    return items;
  }

  $("#searchForm").submit(function(event) {
    event.preventDefault();
    let k = "Search_Text";
    let t = $("#searchTerm").val();
    console.log("Trigger Search for: " + t);
    if (k && t != undefined && t.length > 0) {
      if (getItems(k).length == 0) {
        setItems(k, [t]);
      }
      var vals = searchItems(k, t);
      setItems(k, vals);
      $("#searchStory").empty();
      $.each(vals, function(i, s) {
        $("<a>", {
          name: "search_txt",
          class: "txt-search-story",
          href: "#"
        }).html("<span>" + s + "</span>").appendTo($("#searchStory"));
      });
      //location.reload();
    }
    return false;
  });

  $("#clearStory").click(function() {
    resetItems("Search_Text");
  });
});

It can be helpful to setup small functions to help with common operations. I created functions to Get, Save, and Reset the LocalStorage.

Wrapping with a Form is not necessary yet it can be helpful. For example, I use LastPass and this was causing issues when I hit the Enter key on the Input element. Using a Form, the User can enter text and hit Enter to submit the form. This also work with Mobile devices when they hit “Go” on the mobile keyboard. It removes an amount of code that is no longer needed.

The rest is just cleaned up jQuery code based on your example.

Update

https://jsfiddle.net/Twisty/L876vjmc/55/

Now we have showSearchStory that can be run by an event or on it’s own.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement