Le Qs Le Qs - 15 days ago 4x
Javascript Question

Random variable in key value pairs not interpreted as variable

I have some values i am trying to store in local storage using

pairs. I want the
to be a random value from
but my value is not being seen as a variable

This is the fiddle


and the code

$(document).ready(function () {
$(document).on('click', '.btn-primary', function(){
var num = Math.random();
$('.table tbody').append('<tr class="child"><td>one</td><td><button id="'+num+'" onClick="ae(this.id); function ae(clicked_id) {var items = []; var entry = {\'num\': clicked_id}; items.push(entry);localStorage.setItem(\'entry\',JSON.stringify(items));alert(localStorage.getItem(\'entry\',JSON.stringify(items)));}" type="button" class="invite ">Invite</button></td></tr>');

How can i make
to be seen as a variable?



So localStorage doesn't work so much in these snippets but see the code below or this forked fiddle.

Code changes

  1. Move the function ae() out of the onClick attribute and define it as a regular JS function.
  2. Presuming you want to add each number clicked to the localStorage element entry array, then you need to parse that as json (if it is set) each time instead of making a new array.
  3. Instead of using the onclick attribute, add a click handler for the elements with class name invite, just like you are doing for the elements with class name btn-primary...

function ae(event) {
  var items = JSON.parse(localStorage.getItem('entry'));
  if (items == null || typeof items !== 'object') {
      items = [];
  var entry = {
    'num': event.target.id
  localStorage.setItem('entry', JSON.stringify(items));
$(document).ready(function() {
  $(document).on('click', '.invite', ae);
  $(document).on('click', '.btn-primary', function() {
    var num = Math.random();
    $('.table tbody').append('<tr class="child"><td>one</td><td><button id="' + num + '"type="button" class="invite ">Invite</button></td></tr>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table">

<button class="btn-primary">Add Row