How to store a value (string) in a web page

I would like to store the value of something in my web page for later use by some javascript function. I thought about doing something like this when I have a div with a CategoryID and then put the value in that as HTML.

   <div id="CategoryID"></div>

   $('#categories > li > a').click(function (e) {
      e.preventDefault();
      $('#CategoryID').html = $(this).attr('data-value')
      refreshGrid('Reference');
   });

      

Then later, inside functions like refreshGrid (and some other functions), I could get a value like this:

   var categoryID = $('#CategoryID').val();

      

Does this sound like a good way to store a temporary variable? How about HTML5, there is a way to store values ​​without having to put them inside a div or anything like that. All I need is to have a value that is stored in some on the page.

One more question. If I store the value, this is the correct way to do it:

$('#CategoryID').html = $(this).attr('data-value')

      

+3


source to share


10 replies


Use HiddenField

to store a variable using jquery

like this:

var tempvalue= $(this).attr('data-value');

$('#my-hidden-field').val(tempvalue);

      



Hope this helps you.

+2


source


Use hidden fields on your web page. For example.

<INPUT TYPE=HIDDEN NAME="customerId" VALUE="1234567">

      



And then use .val

in JQuery to work with those values.

+1


source


The function val()

gets the value of the element. But only the inputs matter, so you have to use hidden input to store the data:

<input id="CategoryId" type="hidden" />

      

But you can access any attribute as described below. Just keep in mind that attr()

is the old and the new function name -> prop()

see the comment for correct explanation regarding attr()

andprop()

+1


source


I sometimes use hidden entrances for this purpose on a case-by-case basis.

<input type="hidden" name="CategoryID" id="CategoryID" />

      

Then return it like this:

var categoryID = $('#CategoryID').val();

      

I am using inputs as I feel html which is not markup for the page should not be there.

Sometimes it is easiest to dump a variable from the server to a script.

Example with ASP.NET:

<script type="text/javascript">
//<!--

var categoryID = <%= <output value from server goes here> %>;

//-->
</script>

      

+1


source


You should try using the localStorage API introduced in HTML5 if you are fond of the fact that otherwise storing it in hidden fields is the way to go.

var idForStorage = $('#CategoryID').val();
window.localStorage.setItem('keyToId', idForStorage);

      

and get it from localStorage

var fetchedId = window.localStorage.getItem('keyToId');

      

Note: localstorage only stores values ​​as strings, remember this! :)

Also, if you want to be older browser compatible, remember to check if localStorage exists and implement a different solution.

Something along the lines

if(typeof(window.localStorage) !== 'undefined'){
    //set item or do whatever
} else {
    //implement other solution or throw an exception
}

      

Good luck!

+1


source


Just a thought, but did you consider storing the value in a javascript variable? If you only use it in javascript, why put it in a hidden field or element at all?

Just declare the variable in the global scope if you are not using namespacing / modules, but if you can keep it in the scope of the used module.

Only considerations with this approach would be to reset the variable on page refresh, but if you are using the value on the server, just in a script, then that should be fine.

In general, I would only use hidden input if the server needed to read it.

EDIT

In the comments to the comments, if you are using your javascript intelligently, which involves using a namespace, this approach works with a certain degree of elegance at cluttering your markup with "variable holders"

A very fast scaffold for the namespace .....

in file MyProject.Global.js

//This function is truly global
function namespace(namespaceString) {
   var parts = namespaceString.split('.'),
        parent = window,
        currentPart = '';

   for (var i = 0, length = parts.length; i < length; i++) {
      currentPart = parts[i];
      parent[currentPart] = parent[currentPart] || {};
      parent = parent[currentPart];
   }

   return parent;
}

      

in file MyProject.MyPage.Ui.js

namespace('MyProject.MyPage');

MyProject.MyPage.Ui = function () {

   var self = this;
   self.settings = {};

   function init(options) {
      $.extend(self.settings, options);
        //any init code goes here, eg bind elements
        setValue();
      };
   };

   //this is considered a "private" function
   function setValue(){

       $('#categories > li > a').click(function (e) {
          e.preventDefault();
          self.settings.myValue = $(this).attr('data-value');
          refreshGrid('Reference');
       });
   }

   function getValue(){
     return self.settings.myValue;
   }

   //any function within this return are considered "public"
   return {
      init: init,
      getValue: getValue
   };
};

      

finally on your page ...

$(document).ready(function () {
    var ui = new MyProject.MyPage.Ui();
    ui.init();
}

      

then at any time you can get your value using ...

MyProject.MyPage.getValue()

      

+1


source


There are three ways to store the values ​​as you wish:

  • Cookies: the good old way. It is supported everywhere, but is more suitable for values ​​that need to be stored on different pages and has other restrictions (such as size, number of records, etc.).
  • SessionStorage: Not supported everywhere, but there are shims. It allows you to store a value that will only last for the session. Example:

    sessionStorage.setItem('key', 'value')

    sessionStorage.getItem('key', 'value')

This only accepts strings as keys and values. If you want to store objects, you can use JSON.stringify

to store them and retrieve them later with JSON.parse

.

  • LocalStorage: sibling to sessionStorage, but has no time limit. It allows data to be stored with the same API as sessionStorage, and it is stored over time.
0


source


One more question. If I store the value, this is the correct way to do it:

An easier way to use attributes Data-

with jQuery is to use the .data()

.

<body id="CategoryData" data-value1="someone" data-value2="sometwo">

....

alert( $("#CategoryData").data('value1') ); // popup with text: someone
alert( $("#CategoryData").data('value2') ); // popup with text: sometwo

      

Personally, I would prefer to store all data associated with elements in a wrapper Div

or other elements and use jquery.data.

<table data-locationid="1">
  <tr data-personid="1">
    <td>Jon</td>
    <td>Doe</td>
  </tr>
  <tr data-personid="2">
    <td>Jane</td>
    <td>Doe</td>
  </tr>
</table>

      

HTML5 Data - * Attributes

As of jQuery 1.4.3 HTML data attributes will be automatically inserted into the jQuery data object. Inline dash attribute handling has been changed in jQuery 1.6 to conform to the W3C HTML5 specification.

0


source


If you want to store a value in one part of your JavaScript for access from another part, I would just use a variable:

var categoryID = null;  // set some kind of default

$('#categories > li > a').click(function (e) {
  e.preventDefault();
  categoryID = $(this).attr('data-value');
  refreshGrid('Reference');
});

      

Then when you need a value, just tap categoryID

.

One more question. If I store the value this is the correct way to do it

If you want to set a value as the content of your div element, you must use the jQuery method .html()

or the non-jQuery property .innerHTML

:

$('#CategoryID').html( $(this).attr('data-value') );
// or
$("#CategoryID")[0].innerHTML = $(this).attr('data-value');

      

But if you dont want to use a variable, you are better off using hidden input as stated in other answers, not in a div.

0


source


For browser compatibility, its wiser to use a hidden field, as others have suggested. But for research reasons, if you want to use HTML5, it offers WebStorage. For more information see http://sixrevisions.com/html/introduction-web-storage/

In addition, there is an infrastructure called Lawnchair a proposed solution for html5 mobile applications that requires a lightweight, responsive, simple and elegant save solution.

0


source







All Articles