0

I am a beginner in Javascript/Jquery and I am making a mobile web app using jquery mobile and jquery and I can't figure out how to display all my inputs in one place. No matter how many data I enter into the form it always displays the last entered .Please, any help?

$(document).ready(function() {
   if(localStorage['linrval'],localStorage['linrdate']){
      $('#inrhist').prepend('<div class="inrval">'+localStorage['linrdate']+ '  ----  '   +localStorage['linrval']+ '</div>');
   };

$('#inrbtn').click(function(){
   var inrval=$('input[name=user]').val();
   var inrdate=$('input[name=dateinr]').val();
   localStorage.setItem('linrval',inrval);
   localStorage.setItem('linrdate',inrdate);
   $('#inrhist').prepend('<div class="inrval">'+inrdate+ '  ----  ' +inrval+ '</div>');
   });
Liath
  • 9,913
  • 9
  • 51
  • 81
mihnea2kx
  • 100
  • 8

2 Answers2

0

You have this:

if(localStorage['linrval'],localStorage['linrdate']){...}

Such expression is true if and only if localStorage['linrdate'] is true. The value for localStorage['linrval'] is basically ignored.

Perhaps you want this:

if( localStorage['linrval'] || localStorage['linrdate'] ){...}
                            ^^

You're also overwriting your localStorage values:

localStorage.setItem('linrval',inrval);
localStorage.setItem('linrdate',inrdate);
Álvaro González
  • 142,137
  • 41
  • 261
  • 360
0

Couple of things need to change here every time you need to add into array instead of you update the item value with same property. localStorage only supports strings.

   $(document).ready(function() {

            //localStorage.removeItem("users");

        var userStr = localStorage.getItem('users');

        if (userStr != null && userStr != undefined) {
            var jsonObj = JSON.parse(userStr);

            console.log("onload value", jsonObj);

            $.each(jsonObj.items, function(i, item) {
                $('#inrhist').prepend('<div class="inrval">'+item.user +'--'+item.dateinr+'</div>');
             });
        }

        $('#inrbtn').click(function () {

            var dataItems = { items: [] };

            var inrval = $('input[name=user]').val();
            var inrdate = $('input[name=dateinr]').val();

            var item = { user: inrval, dateinr: inrdate };

            var usersList = localStorage.getItem('users');

            var jsonObj;

            if (usersList == null) {
                dataItems.items.push(item);                  
                jsonObj = JSON.parse(JSON.stringify(dataItems));
            }
            else {
                jsonObj = JSON.parse(usersList);
                jsonObj.items.push(item);
            }

            jsonStr = JSON.stringify(jsonObj);

            console.log(jsonStr);

            localStorage.setItem("users", jsonStr);

            $('#inrhist').prepend('<div class="inrval">' + inrdate + '--' + inrval + '</div>');

        });

    });

LIVE DEMO

Raja Jaganathan
  • 33,099
  • 4
  • 30
  • 33