Dependent Dropdown list in Javascript, jQuery, Json & Ajax - javascript

How can I make it so when I select an option it will only populate that one area?
I only want the specific places in that area.
example picture.]
Example of the output (1)
Example of the output (2)
this is the json code that I want to have a function and connect the two or more files.
json file 1
{
"code": "010000000",
"name": "Ilocos Region",
"altName": "Region I"
}
json file 2
{
"code": "012800000",
"name": "Ilocos Norte",
"altName": null,
"region": "010000000"
},
{
"code": "012900000",
"name": "Ilocos Sur",
"altName": null,
"region": "010000000"
},
{
"code": "013300000",
"name": "La Union",
"altName": null,
"region": "010000000"
},
{
"code": "015500000",
"name": "Pangasinan",
"altName": null,
"region": "010000000"
}
here is the code
html part
<div class="container form-group" style="width:600px; margin-top: 10vh">
<form action="" method="GET" id="addform">
<div class="form-group">
<select name="region" id="region" class="form-control input-sm" required>
<option value="">Select Region</option>
</select>
</div>
<div class="form-group">
<select name="province" id="province" class="form-control input-sm" required>
<option value="">Select Province</option>
</select>
</div>
</form>
</div>
<script>
$(function(){
let regionOption;
let provinceOption;
//FOR REGION
$.getJSON('regions.json', function(result){
regionOption += `<option value="">Select Region</option>`;
$.each(result, function(i, region){
regionOption += `<option value='${region.code}'> ${region.altName}</option>`;
});
$('#region').html(regionOption);
});
//FOR PROVINCE
$('#region').change(function(){
$.getJSON('provinces.json', function(result){
provinceOption += `<option value="">Select Province</option>`;
$.each(result, function(region, province){
provinceOption += `<option value='${province.name}'> ${province.name}</option>`;
});
$('#province').html(provinceOption);
});
});
});
</script>
my failed attempt is this part :
$('#region').change(function(){
if($(this).val() === $(this).val()){
$.getJSON('provinces.json', function(result){
provinceOption += `<option value="">Select Province</option>`;
$.each(result, function(region, province){
provinceOption += `<option value='${province.name}'> ${province.name}</option>`;
});
$('#province').html(provinceOption);
});
}
});

You can use .filter() to filter your json return inside ajax then inside this compare value of select-box with all values of region if they matches get that data . Finally loop through filter datas and show them inside your select-box.
Demo Code :
//just for demo :)
var result = [{
"code": "010000000",
"name": "Ilocos Region",
"altName": "Region I"
}, {
"code": "010000002",
"name": "Ilocos Region2",
"altName": "Region 2"
}]
var json2 = [
{
"code": "012800000",
"name": "Ilocos Norte",
"altName": null,
"region": "010000000"
},
{
"code": "012900000",
"name": "Ilocos Sur",
"altName": null,
"region": "010000000"
},
{
"code": "013300000",
"name": "La Union",
"altName": null,
"region": "010000002"
},
{
"code": "015500000",
"name": "Pangasinan",
"altName": null,
"region": "010000002"
}
]
$(function() {
let regionOption;
let provinceOption;
//FOR REGION
/* $.getJSON('regions.json', function(result) {*/
regionOption += `<option value="">Select Region</option>`;
$.each(result, function(i, region) {
regionOption += `<option value='${region.code}'> ${region.altName}</option>`;
});
$('#region').html(regionOption);
/* });*/
$('#region').change(function() {
var values = $(this).val()
var provinceOption = ""
/*$.getJSON('provinces.json', function(json2) {*/
//filter your json return..
var items = $(json2)
.filter(function(i, n) {
return n.region === values; //get value where region is same
});
provinceOption += `<option value="">Select Province</option>`;
//loop through dates
$.each(items, function(region, province) {
provinceOption += `<option value='${province.name}'> ${province.name}</option>`;
});
$('#province').html(provinceOption);
/* });*/
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="container form-group" style="width:600px; margin-top: 10vh">
<form action="" method="GET" id="addform">
<div class="form-group">
<select name="region" id="region" class="form-control input-sm" required>
<option value="">Select Region</option>
</select>
</div>
<div class="form-group">
<select name="province" id="province" class="form-control input-sm" required>
<option value="">Select Province</option>
</select>
</div>
</form>
</div>

Related

3 level multiple cascanding dropdown using Array

I am trying to create a 3 level dropdown with data, but the second and third dropdowns still show the data as a whole. How to have the second and third dropdown filter data based on related data?
var json = [{
"country": "USA",
"state": "LOS ANGELES",
"city": "LOS ANGELES"
},
{
"country": "USA",
"state": "LOS ANGELES",
"city": "LOS ANGELES 2"
},
{
"country": "USA",
"state": "New York",
"city": "New York",
},
{
"country": "USA",
"state": "New York",
"city": "New York 2",
},
{
"country": "CANADA",
"state": "British Columbia",
"city": "Vancovour",
}
];
for (i = 0; i < json.length; i++) {
$("#country").append("<option value=" + json[i]["country"] + ">" + json[i]["country"] + "</option>");
$("#state").append("<option value=" + json[i]["country"] + ">" + json[i]["state"] + "</option>");
$("#city").append("<option value=" + json[i]["country"] + ">" + json[i]["city"] + "</option>");
}
$("#state").change(function() {
$("#country")[0].selectedIndex = $(this)[0].selectedIndex
$("##city")[0].selectedIndex = $(this)[0].selectedIndex
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="myform" id="myForm">
<select name="opttwo" id="country" size="1">
<option value="" selected="selected">Please select state </option>
</select>
<br>
<br>
<select name="optone" id="state" size="1">
<option value="" selected="selected">Please Select country first</option>
</select>
<br>
<br>
<select name="optthree" id="city" size="1">
<option value="" selected="selected">Please select country first</option>
</select>
</form>
I have tried to make it like this. what should I add?
var json = [{
"country": "USA",
"state": "LOS ANGELES",
"city": "LOS ANGELES"
},
{
"country": "USA",
"state": "LOS ANGELES",
"city": "LOS ANGELES 2"
},
{
"country": "USA",
"state": "New York",
"city": "New York",
},
{
"country": "USA",
"state": "New York",
"city": "New York 2",
},
{
"country": "CANADA",
"state": "British Columbia",
"city": "Vancovour",
}
];
function addElementsFor(c, v, index) {
var tracker = [];
for (var i = 0, o; o = json[i]; i++) {
if (!!v && !!index && o[v] !== json[index][v]) {
continue;
}
if (tracker.indexOf(o[c.id]) !== -1) {
continue;
}
tracker.push(o[c.id]);
var option = document.createElement('option');
option.value = i;
option.innerText = o[c.id];
c.appendChild(option);
}
return c
}
function populateSubCategory(c, v, index) {
var state = document.getElementById(c);
state.disabled = false;
while (state.firstChild) state.firstChild.remove();
var option = document.createElement('option');
option.value = -1;
option.innerText = '----';
state.appendChild(option);
if (index * 1 < 0) return;
return addElementsFor(state, v, index);
}
window.addEventListener('load', function() {
addElementsFor(document.getElementById('country')).addEventListener('change', function(ev) {
populateSubCategory('state', ev.target.id, ev.target.value).addEventListener('change', function(ev) {
populateSubCategory('city', ev.target.id, ev.target.value).addEventListener('change', function(ev) {
if (ev.target.value * 1 < 0) {
return;
}
var country = document.getElementById('country');
var state = document.getElementById('state');
var city = ev.target;
if (json.hasOwnProperty(country.value) && json.hasOwnProperty(state.value) && json.hasOwnProperty(city.value)) {
console.log('country: %s state: %s city: %s', json[country.value]['country'], json[state.value]['state'], json[city.value]['city']);
}
})
})
})
});
<form name="myform" id="myForm">
<select name="opttwo" id="country" size="1">
<option value="-1" selected="selected">Please select state </option>
</select>
<br>
<br>
<select name="optone" id="state" size="1">
<option value="-1" selected="selected">Please Select country first</option>
</select>
<br>
<br>
<select name="optthree" id="city" size="1">
<option value="-1" selected="selected">Please select country first</option>
</select>
</form>
You need to check if there is already a select element with the same content before adding it again or you will end up with duplicates.
Check this thread: https://stackoverflow.com/a/9791018/5211055

How to update json value with dropdown list

Can anyone teach me how can I update json value using the the dropdown list.
In JavaScript
HTML:
<select id="currency" onchange="getSelectValue();">
<option value="Singapore Dollar">Singapore Dollar</option>
<option value="USD">USD</option>
<option value="Malaysia Riggit">Malaysia Riggit</option>
</select>
JSON :
{
"products": [
{
"name": "Apple",
"price": "2.50",
"code": "SGD"
},
{
"name": "Orange",
"price": "2.50",
"code": "SGD"
}
]
}
You can create a select in javascript like this, focus on the <script />
<!DOCTYPE html>
<html lang="en">
<head>
<title>Javascript - Select</title>
</head>
<body>
<div id="main"></div>
</body>
<script>
const {products} = JSON.parse('{ "products": [ { "name": "Apple", "price": "2.50", "code": "SGD" }, { "name": "Orange", "price": "2.50", "code": "SGD" } ] }');
const select = document.createElement("select");
select.id = 'currency';
select.onchange = ({target: {value}}) => console.log(value);
products.forEach(({code, name}) => {
const option = document.createElement("option");
option.label = name;
option.value = code;
select.appendChild(option);
});
const main = document.getElementById('main');
main.appendChild(select);
</script>
</html>
EDIT:
Add the "value" as a param of the function
<select id="currency" onchange="getSelectValue(value)">
<option value="SGD">Singapore Dollar</option>
<option value="USD">USD</option>
<option value="MR">Malaysia Riggit</option>
</select>
and the function definition should look like this:
const getSelectValue = (selectedValue) => {
console.log(selectedValue);
// Your code...
};
Here is the code sample.
var json=JSON.parse( "Your json which you mentioned above");
var products= json.products;
string selectlist="";
if(products.length>0)
{
selectlist += "<select>";
for(var i = 0; i < products.length; i++) {
var currency = json[i];
selectlist += "<option value="+currency.code+"> "+currency.code+" </option>";
}
selectlist += "</select>"
if("body").append(selectlist);
}

AngularJS ng-options setting default select value

app.factory("ParentsFactory", function ($http) {
return $http.get("/home/parents");
})
ParentsFactory.then(function (data) {
$scope.Parents = data.data;
});
<select class="form-control" ng-model="modelparent">
<option value="{{parent.ParentID}}" ng-selected="{{parent.ParentID==2}}" ng-repeat="parent in Parents">{{parent.DocumentNo}} - {{parent.FullName}}</option>
</select>
Remove interpolation braces {{}} from ng-selected and try:
<select class="form-control" ng-model="modelparent">
<option value="{{parent.ParentID}}" ng-repeat="parent in Parents" ng-selected="parent.ParentID==2">{{parent.DocumentNo}} - {{parent.FullName}}</option>
</select>
Edit:
According to your data i have edited my answer:
var app=angular.module("app",[]);
app.controller('Ctrl',['$scope',Ctrl]);
function Ctrl($scope){
$scope.modelparent = "1";
$scope.Parents = [{ "ParentID": 1, "FullName": "Jack", "BirthDate": "/Date(631137600000)/", "BirthPalace": 1, "DocumentType": 1, "DocumentNo": "P544123", "AddDate": "/Date(1483300800000)/", "UpdateDate": null, "LastLoginDate": null },
{ "ParentID": 2, "FullName": "Ammanda", "BirthDate": "/Date(631137600000)/", "BirthPalace": 1, "DocumentType": 1, "DocumentNo": "P5441234", "AddDate": "/Date(1483300800000)/", "UpdateDate": null, "LastLoginDate": null }]
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-controller="Ctrl" ng-app="app">
{{Abc}}
<select class="form-control" ng-model="modelparent">
<option value="{{parent.ParentID}}" ng-repeat="parent in Parents">{{parent.DocumentNo}} {{parent.FullName}}</option>
</select>
</div>

Populate select elements dynamically from json data file using jquery

I'am trying to create search box for state districts and villages , but I'am enable to fetch data into combobox.
I have tried so many other way to get data into select boxes they doesn't work. Below is the code I've so far:
HTML:
<div class="dummy__item">
<select name="state_id" id="state_id" tabindex="1">
<option value="">-- Select state --</option>
</select>
</div>
<div class="dummy__item">
<select name="district_id" id="district_id" tabindex="2">
<option value="">-- Select district --</option>
</select>
</div>
<div class="dummy__item">
<select name="village_id" id="village_id" tabindex="3">
<option value="">-- Select village --</option>
</select>
</div>
JS:
<!-- language: lang-js -->
function loadlist(selobj, url) {
$(selobj).empty();
$(selobj).append('<option value="0">--Select Category--</option>')
$(selobj).append(
$.map(jsonList, function(el, i) {
return $('<option>').val(el.slno).text(el.state)
}));
}
loadlist($('select#state_id').get(0), jsonList);
You can do the following (Check the revision history for a shorter version which made use of underscorejs):
The comments should help you get an idea. check https://api.jquery.com/ for detailed information regarding the jQuery methods used.
$(function() {
insert($('#state_id'), plucker(records, 'state'));
//------------------------^ grabs unique states
//--^ populate state list on DOM ready
$('select').on('change', function() {
var category = this.id.split('_id')[0];
var value = $(this).find('option:selected').text();
switch (category) {
case 'state':
{
insert($('#district_id'), plucker(filter(records, 'state', value),'district'));
//-^ insert plucked results to DOM
//------------------------^ plucks districts from filter results
//--------------------------------^ filters districts belonging to selected state
break;
}
case 'district':
{
insert($('#village_id'), plucker(filter(records, 'district', value),'village'));
break;
}
}
});
function plucker(arr, prop) {
// grabs unique items from the required property such as state, district etc from the results
return $.map(arr, function(item) {
return item[prop]
}).filter(function(item, i, arr) {
return arr.indexOf(item) == i;
});
}
function filter(arr, key, value) {
// filters the records matching users selection
return $.grep(arr, function(item) {
return item[key] == value;
});
}
function insert(elm, arr) { // inserts the results into DOM
elm.find('option:gt(0)').remove();
$.each(arr, function(i,item) {
elm.append($('<option>', {
value: i,
text: item
}));
});
}
});
var records = [{
"slno": "1",
"state": "Maharashtra",
"constituency": "Parbhani",
"mp": "Shri Sanjay Haribhau Jadhav",
"district": "Parbhani",
"block": "Jintur",
"village": "Kehal",
"latitude": "77.7",
"longitude": "19.33"
}, {
"slno": "2",
"state": "Maharashtra",
"constituency": "Shirur",
"mp": "Shri Shivaji Adhalrao Patil",
"district": "Pune",
"block": "Shirur",
"village": "Karandi",
"latitude": "77.7",
"longitude": "19.33"
}, {
"slno": "3",
"state": "Maharashtra",
"constituency": "Amravati",
"mp": "Shri Anandrao Vithoba Adsul",
"district": "Amravati",
"block": "Amravati",
"village": "Yavli Shahid",
"latitude": "77.7",
"longitude": "19.33"
}]
$(function() {
insert($('#state_id'), plucker(records, 'state'));
//------^ populate states list on DOM ready
$('select').on('change', function() {
var category = this.id.split('_id')[0];
var value = $(this).find('option:selected').text();
switch (category) {
case 'state':
{
insert($('#district_id'), plucker(filter(records, 'state', value), 'district'));
break;
}
case 'district':
{
insert($('#village_id'), plucker(filter(records, 'district', value), 'village'));
break;
}
}
});
function plucker(arr, prop) {
// grabs unique items from the required property such as state, district etc from the results
return $.map(arr, function(item) {
return item[prop]
}).filter(function(item, i, arr) {
return arr.indexOf(item) == i;
});
}
function filter(arr, key, value) {
// filters the records matching users selection
return $.grep(arr, function(item, i) {
return item[key] === value;
});
}
function insert(elm, arr) {
// inserts the results into DOM
elm.find('option:gt(0)').remove();
$.each(arr, function(i, item) {
elm.append($('<option>', {
value: i,
text: item
}));
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dummy__item">
<select name="state_id" id="state_id" tabindex="1">
<option value="">-- Select state --</option>
</select>
</div>
<div class="dummy__item">
<select name="district_id" id="district_id" tabindex="2">
<option value="">-- Select district --</option>
</select>
</div>
<div class="dummy__item">
<select name="village_id" id="village_id" tabindex="3">
<option value="">-- Select village --</option>
</select>
</div>
In your above code you have made the following mistake,
1.Extra close bracket
$.map(jsonList, function (el, i) {
return $('<option>').val(el.slno).text(el.state)
}));
Update it as
$.map(jsonList, function (el, i) {
return $('<option>').val(el.slno).text(el.state)
});
The looping of json object
$.map(jsonList.listval, function (el, i) {
$('#state_id').append('<option value="'+el.slno+'" attState="'+el.state+'">'+el.state+'</option>');
});
To avoid multiple times the same state repetition, before inserting the option you need to check if the entry is already exist in option if not exist then add it to the select, for this I have introduced a new option attribute "attState". Please look in to the code you will understand what I have done..
$.map(jsonList.listval, function (el, i) {
if ($("#yourSelect option[attState='" + el.state + "']").length == 0) {
$('#yourSelect').append('<option value="' + el.slno + '" attState="' + el.state + '">' + el.state + '</option>');
}
});
For reference refer
Try:
function createOptiolist(list, name) {
var state = list.map(function(obj) {
return obj[name];
});
return state = state.filter(function(v, i) {
return state.indexOf(v) == i;
});
}
var state = createOptiolist(jsonList.listval, "state");
$.each(state, function(i, el) {
$('#state_id').append('<option value="' + el + '">' + el + '</option>');
});
$('#state_id').on('change', function() {
var state = $(this).find('option:selected').val();
$('#district_id').empty();
$.each(jsonList.listval, function(i, el) {
if (el.state == state) {
$('#district_id').append('<option value="' + el.district + '">' + el.district + '</option>');
}
})
});
$('#district_id').on('change', function() {
var district = $(this).find('option:selected').val();
$('#village_id').empty();
$.each(jsonList.listval, function(i, el) {
if (el.district == district) {
$('#village_id').append('<option value="' + el.slno + '">' + el.village + '</option>');
}
})
});
DEMO
DEMO with ajax
Try this plz
HTML
<div class="dummy__item">
<select name="state_id" id="state_id" tabindex="1">
<option value="">-- Select state --</option>
</select>
</div>
<div class="dummy__item">
<select name="district_id" id="district_id" tabindex="2">
<option value="">-- Select district --</option>
</select>
</div>
<div class="dummy__item">
<select name="village_id" id="village_id" tabindex="3">
<option value="">-- Select village --</option>
</select>
</div>
JQUERY
$(document).ready(function(){
// JSON list
var jsonList = {"listval" : [
{
"slno": "1",
"state": "Maharashtra",
"constituency": "Parbhani",
"mp": "Shri Sanjay Haribhau Jadhav",
"district": "Parbhani",
"block": "Jintur",
"village": "Kehal",
"latitude": "77.7",
"longitude": "19.33"
},
{
"slno": "2",
"state": "Maharashtra",
"constituency": "Shirur",
"mp": "Shri Shivaji Adhalrao Patil",
"district": "Pune",
"block": "Shirur",
"village": "Karandi",
"latitude": "77.7",
"longitude": "19.33"
},
{
"slno": "3",
"state": "TEXAS",
"constituency": "XYZ",
"mp": "Shri ABC",
"district": "dist1",
"block": "block1",
"village": "Yavli Shahid",
"latitude": "77.7",
"longitude": "19.33"
},
{
"slno": "4",
"state": "Maharashtra",
"constituency": "Amravati",
"mp": "Shri Anandrao Vithoba Adsul",
"district": "Amravati",
"block": "Amravati",
"village": "Yavli Shahid",
"latitude": "77.7",
"longitude": "19.33"
}]}
// JSON LIST
function loadlist(selobj, url) {
var categories = [];
$(selobj).empty();
$(selobj).append('<option value="0">--Select Category--</option>')
$(selobj).append(
$.map(jsonList.listval, function (el, i) {
if ($.inArray(el.state, categories)==-1) {
categories.push(el.state);
return $('<option>').val(el.slno).text(el.state);
console.log($(el.state));}
}));
}
loadlist($('#state_id').get(0), jsonList);
});

update html table when dropdown value change

From json i need to update the table based on month and year from javascript.
Any approach is fine for me
For reference i have created the FIDDLEbut it is not complete yet, just want to show the real environment
link: :http://jsfiddle.net/qytdu1zs/1/
HTML
<div class="dropdown">
<select name="one" class="dropdown-select">
<option value="">Select Year</option>
<option value="0">2014</option>
<option value="1">2013</option>
<option value="2">2012</option>
</select>
</div>
<div class="dropdown ">
<select name="two" class="dropdown-select">
<option value="">Select Month</option>
<option value="0">January</option>
<option value="1">February</option>
<option value="2">March</option>
<option value="3">April</option>
<option value="4">May</option>
<option value="5">June</option>
<option value="6">July</option>
<option value="7">August</option>
<option value="8">September</option>
<option value="9">October</option>
<option value="10">November</option>
<option value="11">December</option>
</select>
</div>
html Table
<div id="example1"></div>
Jquery - i have used mustache.js
$.ajax({
url : 'data/front_finance.json',
dataType : 'json',
success : function (json) {
var customer = $('#example1').columns({
data : json,
schema : [{
"header" : "ID",
"key" : "id",
"template" : "{{id}}"
}, {
"header" : "Name",
"key" : "name",
"template" : '{{name}}'
}, {
"header" : "Actual",
"key" : "actual"
}, {
"header" : "Target",
"key" : "target"
}, {
"header" : "Status",
"key" : "status",
"template" : "<img src ='{{status}}' alt='{{status}}'></img>"
}, {
"header" : "Trend",
"key" : "trend",
"template" : "<img src ='{{trend}}' alt='{{trend}}'></img>"
}
]
});
}
});
JSON
[
{
"year": "2013",
"jan": [
{
"id": 1,
"name": "data",
"actual": "17",
"target": "19",
"status": "red",
"trend": "down"
}
],
"Feb": [
{
"id": 2,
"name": "data1",
"actual": "10",
"target": "19",
"status": "red",
"trend": "down"
}
],
"March": [
{
"id": 3,
"name": "data2",
"actual": "34",
"target": "19",
"status": "green",
"trend": "down"
}
]
},
{
"year": "2014",
"jan": [
{
"id": 1,
"name": "data",
"actual": "17",
"target": "19",
"status": "red",
"trend": "down"
}
],
"Feb": [
{
"id": 2,
"name": "data1",
"actual": "10",
"target": "19",
"status": "red",
"trend": "down"
}
],
"March": [
{
"id": 3,
"name": "data2",
"actual": "34",
"target": "19",
"status": "green",
"trend": "down"
}
]
}
]
NEW FIDDLE FIDDLE
$(document).ready(function (){
cloneObj= $("#example1").clone();
$('select[name=one]').on('change', function() {
var selectedYear=($("option:selected", this).text());
if (selectedYear!="Select Year"){
for (var a in data){
if(data[a].year==selectedYear){
objMonth=data[a];
return false;
}
}
}else{
objMonth=null;
}
});
$('select[name=two]').on('change', function() {
var selectedYear=($("option:selected", $('select[name=one]')).text());
if (selectedYear!="Select Year"){
var selectedMonth=($("option:selected", this).text());
var jsonValue=objMonth[MonthMap[selectedMonth]];
$("#example1").replaceWith(cloneObj.clone());
$('#example1').columns({ data : jsonValue});
}else{
alert("Please Select year please");
}
});
});
I'll give you an approach on how to go about this. Now, I don't know the exact html of your table how the td and tr are structured, so I'm not going to be able to give you exact code that you can replicate.
You let the user select the month and year from the dropdown whose value you can get in jquery. What would help here greatly is if you have the option values set according to the way months are stored in the JSON array.
//JSON array is structured somewhat like:
"jan": [
{
"id": 1,
"name": "data",
"actual": "17",
"target": "19",
"status": "red",
"trend": "down"
}
]
//Your HTML could be
<select name="two" class="dropdown-select">
<option value="">Select Month</option>
<option value="jan">January</option>
<option value="Feb">February</option>
<option value="March">March</option>
Although this is not a necessity, this would greatly help in accessing the corresponding values in the JSON array. Otherwise you would require a mapping of the option values or text to the month names in form of an array or a suitable data structure.
var selectedMonth;
var selectedYear;
//Store the information selected from the dropdown menu for month and year respectively
//Assuming the JSON array is named arr
$.each( arr, function( index, value ) {
if (arr[index]['year'] == selectedYear){
var foo = arr[index]['year'][selectedMonth][0]; //Based on your array defintion
//You can access the required info of this object by simply doing:
//foo.id,foo.name,foo.status etc. and update the relevant table elements' html here
}
});
I hope this gets you started in the right direction.
We have a table ABC. In that table we have a column which contains dropdown as select having value as blank, option a, option b. Now, with change with this dropdown I want to update the input field accordingly, i.e; if a is chosen, input field value will be 100, if b is chosen, input field will be 0 and if blank is chosen, input field will be blank , readonly. The input field id is set to input_ where i is 1 to no of rows in the table.
Below is the code for implementing this.
HTML :
<select id="select" onChange="changeEvent(this.options[this.selectedIndex].value);" name="select">
Javascript:
function changeEvent(chosen) {
var table = document.getElementById("ABC");
var rows = document.querySelectorAll('tr');
var rowsArray = Array.from(rows);
table.addEventListener('change', (event) => {
var target = event.target.toString();
var rowIndex = rowsArray.findIndex(row => row.contains(event.target));
var x = table.rows.length;
var id = "input_"+(parseInt(rowIndex) - 2).toString();
if(chosen === "a") {
table.rows[rowIndex].cells.item(3).innerHTML="<td><input value='100' id='"+id+" 'style='width:50px;'></input></td>";
return;
}else if(chosen === "b"){
table.rows[rowIndex].cells.item(3).innerHTML="<td><input value='0' id='"+id+"' readonly style='width:50px;'></input></td>";
return;
}else{
table.rows[rowIndex].cells.item(3).innerHTML="<td><input value='' id='"+id+"' readonly style='width:50px;'></input></td>";
return;
}
})
}

Categories

Resources