I want to get my value from json data - javascript

i have json like this
{
"id":"1",
"name":"Kitchen Set",
"parent_id":"0",
},
{
"id":"2",
"name":"Bedroom",
"parent_id":"0"
},
{
"id":"3",
"name":"Living Room",
"parent_id":"0"
},
{
"id":"4",
"name":"Kitchen Set",
"parent_id":"1",
"price":"1000"
},
{
"id":"5",
"name":"Meja Bar",
"parent_id":"1",
"price":"2000"
},
and i want to add price: to my javascript
here is my question i want to get the price from my json to my javascript how can i do that??
i try this but it doesnt work
load_json_data('Price');
function load_json_data(price)
{
var html_code = '';
$.getJSON('int_fur_fin.json', function(data)
}
and this is my javascript
<script>
$(document).ready(function(){
load_json_data('Interior');
function load_json_data(id, parent_id)
{
var html_code = '';
$.getJSON('int_fur_fin.json', function(data){
html_code += '<option value="">Select '+id+'</option>';
$.each(data, function(key, value){
if(id == 'Interior')
{
if(value.parent_id == '0')
{
html_code += '<option value="'+value.id+'">'+value.name+'</option>';
}
}
else
{
if(value.parent_id == parent_id)
{
html_code += '<option value="'+value.id+'">'+value.name+'</option>';
}
}
});
$('#'+id).html(html_code);
});
}
$(document).on('change', '#Interior', function(){
var Interior_id = $(this).val();
if(Interior_id != '')
{
load_json_data('Furniture', Interior_id);
}
else
{
$('#Furniture').html('<option value="">Select Furniture</option>');
}
});
});
</script>
i use this javascript code to populate my dropdown
<form>
<select name="Interior Details" id="Interior" class="form-control input-lg">
<option value="">Select Interior Details</option>
</select>
<br />
<select name="Furniture" id="Furniture" class="form-control input-lg" required >
<option value="">Select Furniture</option>
</select>
</form>

You can use array.find() method to find the matching element. Also i have modified your JSON as a array.
items.find(t=>t.parent_id ==='1');
DEMO
var items = [{
"id":"1",
"name":"Kitchen Set",
"parent_id":"0",
},
{
"id":"2",
"name":"Bedroom",
"parent_id":"0"
},
{
"id":"3",
"name":"Living Room",
"parent_id":"0"
},
{
"id":"4",
"name":"Kitchen Set",
"parent_id":"1",
"price":"1000"
},
{
"id":"5",
"name":"Meja Bar",
"parent_id":"1",
"price":"2000"
}];
var result = items.find(t=>t.parent_id ==='1');
console.log(result);
EDIT
If you want multiple elements with matching id use array.filter.
var items = [{
"id":"1",
"name":"Kitchen Set",
"parent_id":"0",
},
{
"id":"2",
"name":"Bedroom",
"parent_id":"0"
},
{
"id":"3",
"name":"Living Room",
"parent_id":"0"
},
{
"id":"4",
"name":"Kitchen Set",
"parent_id":"1",
"price":"1000"
},
{
"id":"5",
"name":"Meja Bar",
"parent_id":"1",
"price":"2000"
}];
var result = items.filter(t=>t.parent_id ==='1');
console.log(result);

Related

Dynamic fill dropdown list with depedent JSON files using JQuery

I have 3 dependent JSON files that are related together, which are countries.json, states.json and cities.json and i want to fill 3 dropdowns select box with those json files i have. For the first time i select a country in the first dropdown, i see its states in the second dropdown but the problem comes when i select another country, its states come with the states of the previous selected country.
$(document).ready(function(){
var countryOptions = '';
var stateOptions = '';
var cityOptions = '';
$.getJSON('countries.json', function(data){
countryOptions += '<option value="">Select country</option>';
$.each(data, function(key, country){
countryOptions += '<option value="'+country.id+'">'+country.name+'</option>';
});
$('#country').html(countryOptions);
});
$(document).on('change', '#country', function(){
var country_id = $(this).val();
if(country_id != '')
{
$.getJSON('states.json', function(data){
stateOptions += '<option value="">Select state</option>';
$.each(data, function(key, state){
if(country_id == state.country_id)
{
stateOptions += '<option value="'+state.id+'">'+state.name+'</option>';
}
});
$('#state').html(stateOptions);
});
}
else
{
$('#state').html('<option value="">Select state</option>');
$('#city').html('<option value="">Select city</option>');
}
});
$(document).on('change', '#state', function(){
var state_id = $(this).val();
if(state_id != '')
{
$.getJSON('cities.json', function(data){
cityOptions += '<option value="">Select city</option>';
$.each(data, function(key, city){
if(state_id == city.state_id)
{
cityOptions += '<option value="'+city.id+'">'+city.name+'</option>';
}
});
$('#city').html(cityOptions);
});
}
else
{
$('#city').html('<option value="">Select city</option>');
}
});
});
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container" style="width:600px;">
<h2 align="center">JSON - Dynamic Dependent Dropdown List using Jquery and Ajax</h2><br /><br />
<select name="country" id="country" class="form-control input-lg">
<option value="">Select country</option>
</select>
<br />
<select name="state" id="state" class="form-control input-lg">
<option value="">Select state</option>
</select>
<br />
<select name="city" id="city" class="form-control input-lg">
<option value="">Select city</option>
</select>
</div>
//countries.json
[
{
"id":"1",
"name":"USA"
},
{
"id":"2",
"name":"Canada"
},
{
"id":"3",
"name":"Australia"
}
]
//states.json
[
{
"id":"4",
"name":"New York",
"country_id":"1"
},
{
"id":"5",
"name":"Alabama",
"country_id":"1"
},
{
"id":"6",
"name":"California",
"country_id":"1"
},
{
"id":"7",
"name":"Ontario",
"country_id":"2"
},
{
"id":"8",
"name":"British Columbia",
"country_id":"2"
},
{
"id":"9",
"name":"New South Wales",
"country_id":"3"
},
{
"id":"10",
"name":"Queensland",
"country_id":"3"
}
]
//cities.json
[
{
"id":"11",
"name":"New York city",
"state_id":"4"
},
{
"id":"12",
"name":"Buffalo",
"state_id":"4"
},
{
"id":"13",
"name":"Albany",
"state_id":"4"
},
{
"id":"14",
"name":"Birmingham",
"state_id":"5"
},
{
"id":"15",
"name":"Montgomery",
"state_id":"5"
},
{
"id":"16",
"name":"Huntsville",
"state_id":"5"
},
{
"id":"17",
"name":"Los Angeles",
"state_id":"6"
},
{
"id":"18",
"name":"San Francisco",
"state_id":"6"
},
{
"id":"19",
"name":"San Diego",
"state_id":"6"
},
{
"id":"20",
"name":"Toronto",
"state_id":"7"
},
{
"id":"21",
"name":"Ottawa",
"state_id":"7"
},
{
"id":"22",
"name":"Vancouver",
"state_id":"8"
},
{
"id":"23",
"name":"Victoria",
"state_id":"8"
},
{
"id":"24",
"name":"Sydney",
"state_id":"9"
},
{
"id":"25",
"name":"Newcastle",
"state_id":"9"
},
{
"id":"26",
"name":"City of Brisbane",
"state_id":"10"
},
{
"id":"27",
"name":"Gold Coast",
"state_id":"10"
}
]
How to solve this problem? i have tried so far, i think the error is in the JQuery loop function $.each(data, function(key, state){});
$.getJSON('states.json', function(data){
stateOptions +=
This is appending to your existing data when you get new data. Change it to this:
$.getJSON('states.json', function(data){
stateOptions =
$(document).ready(function(){
var countryOptions = '';
var stateOptions = '';
var cityOptions = '';
$.getJSON('countries.json', function(data){
countryOptions += '<option value="">Select country</option>';
$.each(data, function(key, country){
countryOptions += '<option value="'+country.id+'">'+country.name+'</option>';
});
$('#country').html(countryOptions);
});
$(document).on('change', '#country', function(){
var country_id = $(this).val();
if(country_id != '')
{
$.getJSON('states.json', function(data){
stateOptions = '<option value="">Select state</option>';
$.each(data, function(key, state){
if(country_id == state.country_id)
{
stateOptions += '<option value="'+state.id+'">'+state.name+'</option>';
}
});
$('#state').html(stateOptions);
});
}
else
{
$('#state').html('<option value="">Select state</option>');
$('#city').html('<option value="">Select city</option>');
}
});
$(document).on('change', '#state', function(){
var state_id = $(this).val();
if(state_id != '')
{
$.getJSON('cities.json', function(data){
cityOptions += '<option value="">Select city</option>';
$.each(data, function(key, city){
if(state_id == city.state_id)
{
cityOptions += '<option value="'+city.id+'">'+city.name+'</option>';
}
});
$('#city').html(cityOptions);
});
}
else
{
$('#city').html('<option value="">Select city</option>');
}
});
});
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container" style="width:600px;">
<h2 align="center">JSON - Dynamic Dependent Dropdown List using Jquery and Ajax</h2><br /><br />
<select name="country" id="country" class="form-control input-lg">
<option value="">Select country</option>
</select>
<br />
<select name="state" id="state" class="form-control input-lg">
<option value="">Select state</option>
</select>
<br />
<select name="city" id="city" class="form-control input-lg">
<option value="">Select city</option>
</select>
</div>
Note The code snippet is just for OPs sake. It won't run because it utilizes Get requests.

How append a json data in select box with optgroup

I am a newbie in jquery. I want to display JSON data to my select box. My JSON Data is
{
"Color":[
{
"Id":"1",
"Attrib_name":"Color",
"Attrib_value":"Red"
},
{
"Id":"2",
"Attrib_name":"Color",
"Attrib_value":"Blue"
}
],
"Size":[
{
"Id":"3",
"Attrib_name":"Size",
"Attrib_value":"5.6"
},
{
"Id":"4",
"Attrib_name":"Size",
"Attrib_value":"5.1"
}
]
}
I want to create optgroup with option based on the above json. i.e
<optgroup label="color">
<option>Red</option>
<option>Blue</option>
</optgroup>
<optgroup label="size">
<option>5.6</option>
<option>5.1</option>
</optgroup>
I am stuck on how to start. Please help me to get rid of this.
Just take the result of this code and paste it as HTML
What it does is iterate over your json object and create the elements.
var json = {
"Color":[
{
"Id":"1",
"Attrib_name":"Color",
"Attrib_value":"Red"
},
{
"Id":"2",
"Attrib_name":"Color",
"Attrib_value":"Blue"
}
],
"Size":[
{
"Id":"3",
"Attrib_name":"Size",
"Attrib_value":"5.6"
},
{
"Id":"4",
"Attrib_name":"Size",
"Attrib_value":"5.1"
}
]
}
console.log(
Object.keys(json).map(a=>`<optgroup label="${a}">${json[a].map(b=>`<option>${b.Attrib_value}</option>`).join``}</optgroup>`)
)
Here is a full example of how you can do this. You just have to build your HTML and use a jQuery function to add it in the html file. Check my codepen. Code is also bellow
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"
type="text/javascript"></script>
<select id="mySelect"></select>
<script type="text/javascript">
var data = {
"Color":[
{
"Id":"1",
"Attrib_name":"Color",
"Attrib_value":"Red"
},
{
"Id":"2",
"Attrib_name":"Color",
"Attrib_value":"Blue"
}
],
"Size":[
{
"Id":"3",
"Attrib_name":"Size",
"Attrib_value":"5.6"
},
{
"Id":"4",
"Attrib_name":"Size",
"Attrib_value":"5.1"
}
]
};
var html = "";
for(var option in data){
html += `<optgroup label="`+ option +`">`;
data[option].forEach(function(item){
html += `<option value="` + item["Attrib_value"] + `" >`+
item["Attrib_value"] +`</option>`
});
html += `</optgroup>`;
}
console.log('html',html);
$('#mySelect').html(html);
</script>
Since jQuery allows a nice api to create dom elements so I would use the following approach but other answer will work:
var data = {
"Color":[
{
"Id":"1",
"Attrib_name":"Color",
"Attrib_value":"Red"
},
{
"Id":"2",
"Attrib_name":"Color",
"Attrib_value":"Blue"
}
],
"Size":[
{
"Id":"3",
"Attrib_name":"Size",
"Attrib_value":"5.6"
},
{
"Id":"4",
"Attrib_name":"Size",
"Attrib_value":"5.1"
}
]
};
var select = $('<select/>');
$.each(data, function(g, colors) {
var group = $('<optgroup/>', {label:g});
$.each(colors, function(i, color) {
var option = $('<option/>', {
value: color.Attrib_value,
text: color.Attrib_value
});
select.append(group.append(option));
});
});
$('#dropdown').append(select);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='dropdown'></div>

Populate multi select select2 option from REST API

I have 3 select2 fields where I want to populate them using AJAX from API. My question is, how can I populate the first select field option directly from API and then the second field option is populated also by API but based on my selection(s) from the first select field, same goes for the third one.
For example, below are my code & data:
API
[
{
"id": 1,
"project_type": "tv",
"project_stage": "new",
"project_name": "Project A"
},
{
"id": 2,
"project_type": "game",
"project_stage": "completed",
"project_name": "Project B"
},
{
"id": 3,
"project_type": "game",
"project_stage": "new",
"project_name": "Project C"
},
{
"id": 4,
"project_stage": "completed",
"project_type": "film",
"project_name": "Project D"
}
]
HTML
<div class="group">
<select class="project_type" id="project_type" multiple="multiple">
<option value=""></option>
</select>
<select class="project_status" id="project_status" multiple="multiple"">
<option value=""></option>
</select>
<select class="project_select" id="project_select" multiple="multiple">
<option value=""></option>
</select>
</div>
Javascript
$('#project_type').select2({placeholder: "Select project type",});
$('#project_status').select2({placeholder: "Select project Status",});
$('#project_select').select2({placeholder: "Select project",});
Expected Result :
Now the project_type select field wield populate all of the project type as option and say we select "game" then the project_status option would be :
<select class="project_status" id="project_status" multiple="multiple"">
<option value="completed">Completed</option>
<option value="new">New</option>
</select>
and if we select completed, the third filter would be:
<select class="project_select" id="project_select" multiple="multiple">
<option value="Project B">Project B</option>
</select>
I populated this from jinja2 before and its not dynamic, any help is much appreciated thanks.
UPDATE :
below is my current code, for odd reason even for the first filter, its not populating the option even though I'm getting the data :
$('#project_type').select2({
placeholder: "Select project type",
ajax: {
url: '/api/filter/',
delay: 250,
type: 'GET',
data: function (params) {
var query = {
search: params.term,
type: 'public'
}
return query
},
processResults: function (data) {
var data1 = $.map(data, function (obj, idx) {
console.log(obj.project_type);
return obj;
});
console.log("processResults2:", data1);
return {
results: data1,
};
}
}
});
Here is a snippet implementing Select2 Ajax populate (in cascade):
var data = [
{
"id": 1,
"project_type": "tv",
"project_stage": "new",
"project_name": "Project A"
},
{
"id": 2,
"project_type": "game",
"project_stage": "completed",
"project_name": "Project B"
},
{
"id": 3,
"project_type": "game",
"project_stage": "new",
"project_name": "Project C"
},
{
"id": 4,
"project_stage": "completed",
"project_type": "film",
"project_name": "Project D"
}
];
sel_type();
$('#project_status').select2({placeholder: ""});
$('#project_select').select2({ placeholder: ""});
function sel_type() {
$('#project_type').select2({
placeholder: "Select project type",
ajax: {
type: "POST",
url: '/echo/json/',
data: function(params){
var query={
message:params.term,
data: data
}
return { json: JSON.stringify( query ) }
},
processResults: function (data) {
var grouped = groupBy(data.data, 'project_type');
var data1 = [], i = 0;
for (var k in grouped) {
data1.push({"id": i++, "text": k})
}
return {
results: data1,
};
}
}
});
$('#project_type').on('select2:select', function (e) {
var data = e.params.data;
console.log(data);
sel_status(data.text);
});
}
function sel_status(type) {
$('#project_status').select2({
placeholder: "Select project status",
ajax: {
type: "POST",
url: '/echo/json/',
data: function(params){
var query={
message:params.term,
data: data
}
return { json: JSON.stringify( query ) }
},
processResults: function (data) {
var data1 = $.map(data.data, function (obj, idx) {
if (obj.project_type==type)
return obj;
});
var grouped = groupBy(data1, 'project_stage');
var data1 = [], i = 0;
for (var k in grouped) {
data1.push({"id": i++, "text": k})
}
return {
results: data1,
};
}
}
});
$('#project_status').on('select2:select', function (e) {
var data = e.params.data;
console.log(data);
sel_proj(type, data.text);
});
}
function sel_proj(type, status) {
$('#project_select').select2({
placeholder: "Select project",
ajax: {
type: "POST",
url: '/echo/json/',
data: function(params){
var query={
message:params.term,
data: data
}
return { json: JSON.stringify( query ) }
},
processResults: function (data) {
var data1 = $.map(data.data, function (obj, idx) {
if (obj.project_type==type && obj.project_stage==status) {
obj.id = obj.id || idx;
obj.text = obj.project_name;
return obj;
}
});
return {
results: data1,
};
}
}
});
}
var groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
select {
width:200px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet"/>
<div class="group">
<select class="project_type" id="project_type" multiple="multiple">
<option value=""></option>
</select>
<br/>
<select class="project_status" id="project_status" multiple="multiple">
<option value=""></option>
</select>
<br/>
<select class="project_select" id="project_select" multiple="multiple">
<option value=""></option>
</select>
</div>
but because of the Ajax request it does not work here in StackOverflow.
A working version (using JsFiddle echo) is here: https://jsfiddle.net/beaver71/4nq62nqo/
P.S.: you have to change the uri in Ajax request to yours, and remove POST of data.

Based on select field generate a table from json file

Is it possible to auto create a table from json files based on selected values.
$(document).ready(function(){
$("#dropdown_change").change(function(){
alert("Selected value is : " + document.getElementById("dropdown_change").value);
});
With your given json i'hv made an example. Look into this.
$("#dropdown_change").change(function() {
var val = $(this).val();
alert("Selected value is : " + val);
var projects = PROJECTDETAILS.filter(function(pd) {
return pd['Project key'] == val;
})
if (projects.length) {
var html = '';
projects.map(function(pro) {
html += '<tr>';
for (var i in pro) {
html += '<td>' + pro[i] + '</td>';
}
html += '</tr>';
})
$('table').find('tr').not(':eq(0)').remove();
$('table').show().append(html);
}
});
var PROJECTDETAILS = [{
"Project key": "Bluesky",
"Employee Name": "anusha",
"Issue Id": "0011",
"Charge No": "1111",
"Hours": "10"
}, {
"Project key": "Bluesky",
"Employee Name": "anusha",
"Issue Id": "00123",
"Charge No": "1111",
"Hours": "10"
}, {
"Project key": "project2",
"Employee Name": "kavya",
"Issue Id": "00452",
"Charge No": "1111",
"Hours": "10"
}]
$(document).ready(function() {
$("#dropdown_change").change(function() {
var val = $(this).val();
alert("Selected value is : " + val);
var projects = PROJECTDETAILS.filter(function(pd) {
return pd['Project key'] == val;
})
if(projects.length){
var html = '';
projects.map(function(pro){
html+='<tr>';
for(var i in pro){
html+='<td>'+pro[i]+'</td>';
}
html+='</tr>';
})
$('table').find('tr').not(':eq(0)').remove();
$('table').show().append(html);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown_change">
<option value="Bluesky">Bluesky</option>
<option value="project2">project2</option>
</select>
<table style="display: none">
<tr><th>Project key</th><th>Employee Name</th><th>Issue Id</th><th>Charge No</th><th>Hours</th></tr>
</table>

Dynamically populating Select options with jQuery

I'm looking for a better way to handle dynamic populating of my options using JS and JQuery. What I have is working but I am looking for a way to not have t ore-write the function each time I need to populate a list.
Fiddle
And what I am doing is populating these:
<label for="recordPurchaseTimeFrameID" class="input required">When would you like to move?</label>
<select name="recordPurchaseTimeFrameID" id="recordPurchaseTimeFrameID" class="inputclass pageRequired" title="Select a Time Frame">
<label for="recordPurchasePriceRangeID" class="input required">Purchase price range:</label>
<select name="recordPurchasePriceRangeID" id="recordPurchasePriceRangeID" class="inputclass pageRequired" title="Select a Price Range">
Using these scripts:
var rPTJsonListItems= "";
for (var i = 0; i < rPTJsonList.recordPurchaseTimeTable.length; i++){
rPTJsonListItems+= "<option value='" + rPTJsonList.recordPurchaseTimeTable[i].recordPurchaseTimeValue + "'>" + rPTJsonList.recordPurchaseTimeTable[i].recordPurchaseTimeAmount + "</option>";
};
$("#recordPurchaseTimeFrameID").html(rPTJsonListItems);
var rPPJsonListItems= "";
for (var i = 0; i < rPPJsonList.recordPurchasePriceTable.length; i++){
rPPJsonListItems+= "<option value='" + rPPJsonList.recordPurchasePriceTable[i].recordPurchasePriceValue + "'>" + rPPJsonList.recordPurchasePriceTable[i].recordPurchasePriceAmount + "</option>";
};
$("#recordPurchasePriceRangeID").html(rPPJsonListItems);
And using this to populate the dropdowns:
var rPTJsonList = {
"recordPurchaseTimeTable" :
[
{"recordPurchaseTimeValue" : "","recordPurchaseTimeAmount" : "Select"},
....
]};
var rPPJsonList = {
"recordPurchasePriceTable" :
[
{"recordPurchasePriceValue" : "","recordPurchasePriceAmount" : "Select"},
{"recordPurchasePriceValue" : "75k-100k","recordPurchasePriceAmount" : "$75,000 - $100,000"},
....
});
So what I'd like is to have just one main function that populates each unique ID based on it's correlating JSON.
Anyone have any suggestions?
I would suggest you simplify your data as a collection, instead of nested objects, that way you can abstract more easily:
var timeTable = [{
"recordPurchaseTimeValue": "",
"recordPurchaseTimeAmount": "Select"
}, {
"recordPurchaseTimeValue": "3-6",
"recordPurchaseTimeAmount": "3-6 months"
}, {
"recordPurchaseTimeValue": "6-9",
"recordPurchaseTimeAmount": "6-9 months"
}, {
"recordPurchaseTimeValue": "9-12",
"recordPurchaseTimeAmount": "9-12 months"
}, {
"recordPurchaseTimeValue": "12",
"recordPurchaseTimeAmount": "Over 12 months"
}];
var priceTable = [{
"recordPurchasePriceValue": "",
"recordPurchasePriceAmount": "Select"
}, {
"recordPurchasePriceValue": "75k-100k",
"recordPurchasePriceAmount": "$75,000 - $100,000"
}, {
"recordPurchasePriceValue": "100k-125k",
"recordPurchasePriceAmount": "$100,000 - $125,000"
}, {
"recordPurchasePriceValue": "125k-150k",
"recordPurchasePriceAmount": "$125,000 - $150,000"
}, {
"recordPurchasePriceValue": "150k-200k",
"recordPurchasePriceAmount": "$150,000 - $200,000"
}, {
"recordPurchasePriceValue": "200k-250k",
"recordPurchasePriceAmount": "$200,000 - $250,000"
}, {
"recordPurchasePriceValue": "250k-300k",
"recordPurchasePriceAmount": "$250,000 - $300,000"
}, {
"recordPurchasePriceValue": "300k-350k",
"recordPurchasePriceAmount": "$300,000 - $350,000"
}, {
"recordPurchasePriceValue": "350k-400k",
"recordPurchasePriceAmount": "$350,000 - $400,000"
}, {
"recordPurchasePriceValue": "400k-500k",
"recordPurchasePriceAmount": "$400,000 - $500,000"
}, {
"recordPurchasePriceValue": "500k-700k",
"recordPurchasePriceAmount": "$500,000 - $700,000"
}, {
"recordPurchasePriceValue": "700k-900k",
"recordPurchasePriceAmount": "$700,000 - $900,000"
}, {
"recordPurchasePriceValue": "900k",
"recordPurchasePriceAmount": "$900,000"
}];
Then you can create a function to populate selects given the data as a collection, and the attributes to set on each generated option, that map to a given key.
We can use document fragments to improve performance, as you only need to append to the DOM once.
Demo: http://jsfiddle.net/Ls4mD/
function populateSelect(select, data, attrs) {
var frag = document.createDocumentFragment();
data.forEach(function(option) {
var opt = document.createElement('option');
for (var i in attrs) {
opt[i] = option[attrs[i]];
}
frag.appendChild(opt);
});
select.appendChild(frag.cloneNode(true));
}
var time = document.getElementById('recordPurchaseTimeFrameID');
var price = document.getElementById('recordPurchasePriceRangeID');
populateSelect(time, timeTable, {
value: 'recordPurchaseTimeValue',
textContent: 'recordPurchaseTimeAmount'
});
populateSelect(price, priceTable, {
value: 'recordPurchasePriceValue',
textContent: 'recordPurchasePriceAmount'
});

Categories