eHow launches Android app: Get the best of eHow on the go.

How To

How to setup a JSON (JavaScript Object Notation) variable

Member
By rpromjr
User-Submitted Article
(1 Ratings)

In this article I will teach you how to make use of JSON (JavaScript Object Notation) variables to make organizing your JavaScript code easier.

Difficulty: Moderate
Instructions

Things You'll Need:

  • Computer
  • Text editor
  • Website or test on your personal computer
  1. Step 1

    In your javascript area (probably in your .js file that you will link to from your HTML(ASP, PHP, JSP, or any page displaying HTML content), type the following:

    var displayMessages = {
    sayHello: "hello",
    sayBye: "bye"
    };

  2. Step 2

    Now in any function also in your javascript if you want to refer to "hello" or "bye" you can put:
    displayMessages.sayHello

    example: alert(displayMessages.sayHello); // will alert "hello" to the user

  3. Step 3

    If you want to make globally (within your javascript file) accessible object references, use the following JSON:
    var myObjects = {
    objectOne: function() {
    return document.getElementById('myObjectsIdHere');
    },
    objectTwo: function() {
    return document.getElementById('myObjectsIdHere2');
    }
    };

  4. Step 4

    Then, if you want to refer to that object later on, instead of always calling document.getElementById('myObjectsIdHere'), you can just put:
    myObjects.objectOne();

    example: var objectOne = myObjects.objectOne();
    objectOne.value = "a new value!";

  5. Step 5

    Of course this isn't necessary to do, but I like to organize my javascript in this manner in case the object I'm referring to changes, I do not have to change many document.getElementById()'s, just the one in the myObjects var.

Tips & Warnings
  • Organize your code to be human legible and understandable!
  • Naming variables and functions/methods to short acronyms can make code very difficult to understand. Make it more organized but not always shorter.
Subscribe

Post a Comment

Post a Comment

Related Ads

  • Have you done this? Click here to let us know.
I Did This
Get Free Computers Newsletters

Copyright © 1999-2009 eHow, Inc. Use of this web site constitutes acceptance of the eHow Terms of Use and Privacy Policy.   en-US Portions of this page are modifications based on work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License.

eHow Computers
eHow_eHow Technology and Electronics