Le Qs Le Qs - 2 months ago 6
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

key:value
pairs. I want the
key
to be a random value from
Math.random()
but my value is not being seen as a variable

This is the fiddle

https://jsfiddle.net/ps4xs60x/27/

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
num
to be seen as a variable?

Answer

Disclaimer:

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
  };
  items.push(entry);
  localStorage.setItem('entry', JSON.stringify(items));
  alert(localStorage.getItem('entry'));
}
$(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">
  <tbody></tbody>
</table>

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