2

I have this JSON Object.

{ 
  "headerContent": [
    {
      "name": "User Id",
      "key": "userId",
      "type": "text",
      "default": "Enter User Id"
    },
    {
      "name": "User Name",
      "key": "userName",
      "type": "text",
      "default": "Enter User Name"
    },
    {
      "name": "Password",
      "key": "password",
      "type": "password",
      "default": "Enter Password"
    },
    {
      "name": "Mobile Number",
      "key": "mobileNumber",
      "type": "text",
      "default": "Enter Mobile Number"
    },
    {
      "name": "User Category",
      "key": "userCategory",
      "type": "select",
      "default": "Select Category",
      "options" : ["Admin", "Client", "Regulator"]
    },
    {
      "name": "E-Mail",
      "key": "email",
      "type": "text",
      "default": "Enter Email"
    },
    {
      "name": "User Access",
      "key": "userAccess",
      "type": "select",
      "default": "Select User Access",
      "options" : ["All", "Site"]
    }
  ],
  "bodyContent": [
    {
      "userId": "user_1",
      "userName": "DemoUser",
      "mobileNumber": "99999999",
      "userCategory" : "Admin",
      "email" : "demo@kl.com",
      "userAccess" : "All"
    }
  ]
}

The headerContent describes the attributes of bodyContent. Now, by default all data in the object (like user_1) will be displayed in details. In the html page I have a select box containing 3 values [Admin, Client, Regulator]; which are 3 different user category. When I select any of them, I want to display data based on the selection.

My HTML page contains a select box to select the category.

 <script src="JSCode.js"></script>
 <select id='listSelect' onChange="updateList()">
    <option value='' selected >All</option> 
    <option value='admin'>Admin</option>
    <option value='client'>Client</option>
    <option value='regulator'>Regulator</option>
</select>
<div id='details'> </div>
Nisfan
  • 141
  • 2
  • 14

3 Answers3

3

JSFiddle here

HTML

<table align='center' >
    <tr>
        <td> <select id='listSelect' onChange="updateList()">
            <option value='' selected >All</option> 
            <option value='Admin'>Admin</option>
            <option value='Client'>Client</option>
            <option value='Regulator'>Regulator</option>
        </select></td>
   </tr>
</table>
<div id="result"></div>

JS

var jsonObj = { 
  "headerContent": [
    {
      "...": "..."
    }
  ],
  "bodyContent": [
    {
      "userId": "user_1",
      "userName": "DemoUser",
      "mobileNumber": "99999999",
      "userCategory" : "Admin",
      "email" : "demo@kl.com",
      "userAccess" : "All"
    },
    {
      "userId": "user_2",
      "userName": "DemoUser",
      "mobileNumber": "99999999",
      "userCategory" : "Client",
      "email" : "demo@kl.com",
      "userAccess" : "All"
    }
  ]
};

function searchJSON (json, content, where, is) {
    content = json[content];
    var result = [];
    for (var key in content) {
        if (content[key][where] == is || is == '') {
            result.push(content[key]);
        }
    }
    return result;
}

function printObj (obj, container) {
    var html = '<table>';
    for (var i in obj) {
        for (var j in obj[i]) {
            html += '<tr><td>' + j + '</td><td>' + obj[i][j] + '</td></tr>';
        }
        html += '<tr><td class="black"></td><td class="black"></td></tr>';
    }
    document.getElementById(container).innerHTML = html;
}

function updateList () {
    var e = document.getElementById("listSelect");
    var value = e.options[e.selectedIndex].value;
    printObj(searchJSON(jsonObj, 'bodyContent', 'userCategory', value), 'result');
}

updateList();

On change it executes updateList(). This function gets the value of the element. Then it executes searchJSON(). This function needs the data (jsonObj), the content in your data (in your case bodyContent), the key you are looking for (in your case userCategory) and the value you are looking for. The function loops through the data object and searches for the key. If the value is the same as your select, it adds the object to an array. When the loop is complete it returns the result.

Last function is a simple print function to place the data inside your html. To make sure it gets printed first time, just run the updateList() once.

LOADING .JSON SO link

var xmlhttp;

if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
} else {
    // code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
       if(xmlhttp.status == 200){
           jsonObj = xmlhttp.responseText;
       }
       else if(xmlhttp.status == 400) {
          alert('There was an error 400')
       }
       else {
           alert('something else other than 200 was returned')
       }
    }
}

xmlhttp.open("GET", "jsonInfo.json", true);
xmlhttp.send();
Community
  • 1
  • 1
Thalsan
  • 3,462
  • 1
  • 9
  • 12
  • bt. I have a little problem. The JSON data are stored in a `jsonInfo.json` file. So, first I have to assign the contents of this file to a json object. Like `var jsonObj = content('jsonInfo.json');` – Nisfan May 20 '15 at 11:40
  • Take a look at: [http://stackoverflow.com/questions/8567114/how-to-make-an-ajax-call-without-jquery](http://stackoverflow.com/questions/8567114/how-to-make-an-ajax-call-without-jquery) You can use an AJAX call to read the file. Making an edit in my post. Can't test it atm, but it should work. – Thalsan May 20 '15 at 11:53
0

You can use this way..

var data;
for (var key in data) {
   var value = data[key];
   alert(key + ", " + value);
}
user3774874
  • 53
  • 1
  • 6
  • actually, I want display data objects in the json object named `bodyContent`. If the select box have the value `All` , list all data in it. If select box have the value `Admin`, list the data in `bodyContent` object where `userCategory`=`Admin`. – Nisfan May 20 '15 at 07:06
0

You can do something like this:

var data = { 
  "headerContent": [
    {
      "name": "User Id",
      "key": "userId",
      "type": "text",
      "default": "Enter User Id"
    },
    {
      "name": "User Name",
      "key": "userName",
      "type": "text",
      "default": "Enter User Name"
    },
    {
      "name": "Password",
      "key": "password",
      "type": "password",
      "default": "Enter Password"
    },
    {
      "name": "Mobile Number",
      "key": "mobileNumber",
      "type": "text",
      "default": "Enter Mobile Number"
    },
    {
      "name": "User Category",
      "key": "userCategory",
      "type": "select",
      "default": "Select Category",
      "options" : ["Admin", "Client", "Regulator"]
    },
    {
      "name": "E-Mail",
      "key": "email",
      "type": "text",
      "default": "Enter Email"
    },
    {
      "name": "User Access",
      "key": "userAccess",
      "type": "select",
      "default": "Select User Access",
      "options" : ["All", "Site"]
    }
  ],
  "bodyContent": [
    {
      "userId": "user_1",
      "userName": "DemoUser",
      "mobileNumber": "99999999",
      "userCategory" : "Admin",
      "email" : "demo@kl.com",
      "userAccess" : "All"
    }
  ]
}

$("#listSelect").change(function(){
var opt = $(this).val();
    console.log(opt);
    $.each(data.headerContent,function(i,v){
        if(v.hasOwnProperty("options"))
        {
           var index = -1;
            v.options.some(function(element, i) {
                if (opt === element.toLowerCase()) {
                    index = i;
                    return true;
                }
            });
           if(index != -1)
           {
               $("#details").text(v.name + " " + v.key);
           }
           
           
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table align='center'>
    <tr>
        <td></td>
    </tr>
    <tr>
        <td>
            <select id='listSelect' onChange="">
                <option value='' selected>All</option>
                <option value='admin'>Admin</option>
                <option value='client'>Client</option>
                <option value='regulator'>Regulator</option>
            </select>
        </td>
    </tr>
    <tr>
        <td>
            <p id='details'>
            </P>
        </td>
    </tr>
</table>
Mox Shah
  • 2,825
  • 2
  • 23
  • 40