update html table when dropdown value change - javascript

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;
}
})
}

Related

Dropdown with database searching dynamic dependence

Currently, I was trying to make multiple chain dropdown lists.
The data was json format something like.
[{"y":1,"x":1,"name":"5M","value":0},
{"y":1,"x":2,"name":"5L","value":2},
{"y":1,"x":3,"name":"5K","value":16},
{"y":1,"x":4,"name":"5J","value":0},
{"y":1,"x":5,"name":"5H","value":0},
{"y":1,"x":6,"name":"5G","value":1},
{"y":1,"x":7,"name":"5F","value":8},
The dropdown idealized was like the footer filter of this example from datatable.
http://live.datatables.net/gejojiqu/1/edit
All of the dropdown select lists can be dynamic dependent after one or many attributes (column) were selected.
For example like when I select the 1st dropdown list which belongs to the "name" attribute with "Bradley Greer", the "position" dropdown select value will only remain "Software Engineer" and so on the other dropdown select value.
Any idea or guidance that how can I achieve this dropdown?
I search for a lot of related guidance about cascading dropdowns non of their data format was similar to mine.
Any help was appreciated.
I manage to find the solution by myself by using jQuery and struggling for a night:
const my data = [
{
"Data": "aaa",
"Media": "1",
"Row": "1",
"Column": "3",
"Code": "24",
},
{
"Data": "aaa",
"Media": "2",
"Row": "1",
"Column": "1",
"Code": "24",
},
{
"Data": "aba",
"Media": "3",
"Row": "1",
"Column": "3",
"Code": "24",
},
{
"Data": "aab",
"Media": "4",
"Row": "1",
"Column": "2",
"Code": "24",
},
{
"Data": "aab",
"Media": "1",
"Row": "2",
"Column": "1",
"Code": "24",
},
{
"Data": "aab123",
"Media": "1",
"Row": "2",
"Column": "1",
"Code": "23",
},
]
mydata.forEach(function(row,index) {
mydata[index] = Object.values(mydata[index]);
});
function makeDropDown(data,filtersAsArray,targetElement){
const filteredArray = filterArray(data, filtersAsArray);
const uniqueList = getUniqueValues(filteredArray,filtersAsArray.length);
populateDropDown(targetElement,uniqueList);
}
function applyDropDown(){
const selectLevel1Value = document.getElementById("level1").value;
const selectLevel2 = document.getElementById("level2");
makeDropDown(mydata, [selectLevel1Value], selectLevel2);
applyDropDown2();
applyDropDown3();
applyDropDown4();
}
function applyDropDown2(){
const selectLevel1Value = document.getElementById("level1").value;
const selectLevel2Value = document.getElementById("level2").value;
const selectLevel3 = document.getElementById("level3");
makeDropDown(mydata, [selectLevel1Value, selectLevel2Value], selectLevel3);
}
function applyDropDown3(){
const selectLevel1Value = document.getElementById("level1").value;
const selectLevel2Value = document.getElementById("level2").value;
const selectLevel3Value = document.getElementById("level3").value;
const selectLevel4 = document.getElementById("level4");
makeDropDown(mydata, [selectLevel1Value, selectLevel2Value, selectLevel3Value], selectLevel4);
}
function applyDropDown4(){
const selectLevel1Value = document.getElementById("level1").value;
const selectLevel2Value = document.getElementById("level2").value;
const selectLevel3Value = document.getElementById("level3").value;
const selectLevel4Value = document.getElementById("level4").value;
const selectLevel5 = document.getElementById("level5");
makeDropDown(mydata, [selectLevel1Value, selectLevel2Value, selectLevel3Value, selectLevel4Value], selectLevel5);
}
function afterDocumentLoads(){
populateFirstLevelDropDown();
applyDropDown();
}
function getUniqueValues(data,index){
const uniqueOptions = new Set();
data.forEach(r => uniqueOptions.add(r[index]));
return [...uniqueOptions];
}
function populateFirstLevelDropDown(){
const uniqueList = getUniqueValues(mydata,0);
const el = document.getElementById("level1");
populateDropDown(el,uniqueList);
}
function populateDropDown(el,listasArray){
el.innerHTML = "";
listasArray.forEach(item => {
const option = document.createElement("option");
option.textContent = item;
el.appendChild(option);
});
}
function filterArray(data, filtersAsArray){
return data.filter(r => filtersAsArray.every((item,i) => item === r[i]));
}
document.getElementById("level1").addEventListener("change",applyDropDown);
document.getElementById("level2").addEventListener("change",applyDropDown2);
document.addEventListener("DOMContentLoaded", afterDocumentLoads);
$(document).ready(function() {
$('.js-example-basic-single').select2();
});
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
</head>
<label>Data</label>
<select class="js-example-basic-single" id="level1" name="level1"></select>
<label>Media</label>
<select class="js-example-basic-single" id="level2" name="level2"></select>
<label>Row</label>
<select class="js-example-basic-single" id="level3" name="level3"></select>
<label>Column</label>
<select class="js-example-basic-single" id="level4" name="level4"></select>
<label>Code</label>
<select class="js-example-basic-single" id="level5" name="level5"></select>
Fiddle

Angularjs drop-down select dynamically

Hi am a beginner in Angularjs, I want to select drop-down selected dynamically.
I refer some blogs but I don't understand that.
This is my HTML code:
<select class="form-control" name="category_id" ng-model="formData.category_id" ng-options="sub_directory.id as sub_directory.name for sub_directory in formData.getSubDirectories" ng-required="true">
<option value="">Select Sub Directory</option>
</select>
Js code:
$scope.getData = function() {
return webServices.getSync('getshops/' + $scope.Id).then(function(getData) {
if (getData.status == 200) {
$scope.formData = getData.data;
console.log($scope.formData);
} else {
$rootScope.$emit("showerror", getData);
}
});
}
$scope.getSubDirectories = function()
{
return webServices.getSync('getSubDirectories').then(function(getData)
{
$rootScope.loading = false;
if (getData.status == 200)
{
$scope.formData.getSubDirectories = getData.data;
} else {
$rootScope.$emit("showerror", getData);
}
//console.log($scope.formData.getSubDirectories);
});
}
My result in console
{
"id": 1,
"membership_type_id": 1,
"name": "Kallyan",
"address": "100 feet road",
"location": "Coimbatore",
"description": "Test",
"banner_image": "upload/directory/contact/directoryMsrq4NhsD1.jpg",
"business_days": [
"M",
"T",
"W",
"Th",
"F",
"S"
],
"start_time": "2019-01-10T09:01:00+05:30",
"end_time": "2019-01-10T10:01:00+05:30",
"contact_number": "9874563210",
"latitude": 11.2,
"longitude": 9.5,
"is_certified": 1,
"status": 3,
"rating": 0,
"is_online_order": 1,
"created_at": "1970-01-01 05:30:01",
"created_by": 0,
"is_active": 1,
"updated_at": "2019-01-09 18:14:22",
"updated_by": 0,
"status_updated_by": 0,
"status_updated_on": "2019-01-09 18:14:22",
"priority": 0,
"comments": "Test",
"additional_information": "",
"old_banner_image": "directoryMsrq4NhsD1.jpg",
"sub_directory": "Jewellery",
"getSubDirectories": [
0: {id: 2, name: "Jewellery", image: "directory5Wltlbhkwl.jpg", thumbnail_image: "directory5Wltlbhkwl.jpg", isparent: 1, …}
1: {id: 3, name: "Mobile", image: "directoryjWQeyCQlGe.jpg", thumbnail_image: "directoryjWQeyCQlGe.jpg", isparent: 1, …}
2: {id: 6, name: "KPN", image: "directoryC8qEC3o3Gh.jpg", thumbnail_image: "directoryC8qEC3o3Gh.jpg", isparent: 1, …}
]
}
My result page:
Here I want to select sub_directory: Jewellery as selected drop-down value.
I don't understand this code in HTML ng-options="sub_directory.id as sub_directory.name for sub_directory in formData.getSubDirectories".
Please give the answer. Thanks in advance.
Try like this way.
<select class="form-control" name="category_id" ng-model="formData.category_id" ng-options="sub_directory.id as sub_directory.name for sub_directory in formData.getSubDirectories" ng-required="true" ng-init="selected='Jewellery'">
<option value="">Select Sub Directory</option>
</select>
I have add this line ng-init="selected='Jewellery'" in your select tag.
<select class="account-form" ng-model="formData.category_id" id="category_id" name="category_id">
<option value="">---Select---</option>
<option ng-repeat="sub_directory.id as sub_directory.name for sub_directory in formData.getSubDirectories" ng-selected="sub_directory.id == 1">
{{sub_directory.name}}
</option>
</select>
Finally i got a result
<select class="form-control" ng-model="formData.category_id" ng-options="directory.id as directory.name for directory in formData.getSubDirectories" ng-init="formData.category_id='2'">
<option value="">Select Sub Directory</option>
</select>

Change Variable Value using a function with select values

How can I change the value of a variable which is outside a function. I want the variable "yr" in my code to be updated with a value from select form by the function update variable.
I looking to update the variable "yr", with the value from the drop down list in my html below. Then I want to use the value of "yr" in another variable called chart4. I have updated the code below.
var yr = "2017";
function updatevariable(data) {
yr = data;
console.log(yr);
};
var chart4 = {
"columns": [
{
"dimension": "dx",
"items": [
{
"id": "fbfJHSPpUQD"
}
]
}
],
"rows": [
{
"dimension": "pe",
"items": [
{
"id": yr
}
]
}
],
"filters": [
{
"dimension": "ou",
"items": [
{
"id": "fdc6uOvgoji"
}
]
}
],
"el": "chart4"
};
<select id="year" name="year" onchange="updatevariable(this.value)">
<option value="2017">2017</option>
<option value="2016">2016</option>
<option value="2015">2015</option>
<option value="2014">2014</option>
</select>
The function you written is correct one to change the value of the variable outside the function.
And a simple demo to understand that,
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
var yr = "2017";
function updatevariable(data) {
yr = data;
};
function print(){
alert(yr);
console.log(yr);
}
</script>
</head>
<body>
<select id="year" name="year" onchange="updatevariable(this.value)">
<option value="2017">2017</option>
<option value="2016">2016</option>
<option value="2015">2015</option>
<option value="2014">2014</option>
</select>
<button onclick="print()">Updated date</button>
</body>
</html>
Simply adding an assignment to the yr inside char4 every time the drop down menu is changed.
Hope this will help!
var yr = "2017";
function updatevariable(data) {
yr = data;
chart4.rows[0].items[0].id = yr;
console.log(chart4.rows[0].items[0].id);
};
var chart4 = {
"columns": [
{
"dimension": "dx",
"items": [
{
"id": "fbfJHSPpUQD"
}
]
}
],
"rows": [
{
"dimension": "pe",
"items": [
{
"id": yr
}
]
}
],
"filters": [
{
"dimension": "ou",
"items": [
{
"id": "fdc6uOvgoji"
}
]
}
],
"el": "chart4"
};

Default Value of select box not being set

I have a data structure like so:
$scope.personalityFields.traveller_type = [
{"id":1,"value":"Rude", "color":"red"},
{"id":2,"value":"Cordial", "color":"yellow"},
{"id":3,"value":"Very Friendly", "color":"green"},
];
And a select box that looks like so:
<select map-value name="traveller_type" ng-init="init_select()" class="full-width" ng-model="traveller_type" ng-options="item as item.value for item in personalityFields.traveller_type">
<option value="" disabled selected> Choose ...</option>
</select>
How do I set the value of the select box to a value based on a response that maps to the "value" field in the attached JSON? Please help !
So if in the response, the traveller_type is field is set to "Rude", I would want the value of "Rude" to be set in the select box.
This what the response looks like:
someObject = {
traveller_type: "Rude"
}
this needs to be displayed on the select box
If you have only value("Rude","Cordial","Friendly") back from response, you have to change ngOptions syntax to be ng-options="item.vaue as item.value for item in personalityFields.traveller_type"(bind item.value to options)
angular.module("app", [])
.controller("myCtrl", function($scope) {
$scope.traveller_type = 'Rude';
$scope.personalityFields = {
"traveller_type": [{
"id": 1,
"value": "Rude",
"color": "red"
},
{
"id": 2,
"value": "Cordial",
"color": "yellow"
},
{
"id": 3,
"value": "Very Friendly",
"color": "green"
},
]
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
<select map-value name="traveller_type" class="full-width" ng-model="traveller_type" ng-options="
item.vaue as item.value for item in personalityFields.traveller_type">
<option value="" disabled selected> Choose ...</option>
</select>
{{traveller_type}}
</div>
Else you have entire object({"id":1,"value":"Rude", "color":"red"}) back from response, you have to change ngOptions syntax to be ng-options="item as item.value for item in personalityFields.traveller_type track by item.value"(use track by to only compare value property)
angular.module("app", [])
.controller("myCtrl", function($scope) {
$scope.traveller_type = {
"id": 1,
"value": "Rude",
"color": "red"
};
$scope.personalityFields = {
"traveller_type": [{
"id": 1,
"value": "Rude",
"color": "red"
},
{
"id": 2,
"value": "Cordial",
"color": "yellow"
},
{
"id": 3,
"value": "Very Friendly",
"color": "green"
},
]
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
<select map-value name="traveller_type" class="full-width" ng-model="traveller_type" ng-options="
item as item.value for item in personalityFields.traveller_type track by item.value">
<option value="" disabled selected> Choose ...</option>
</select>
{{traveller_type}}
</div>
There are a couple of things wrong with your code, below is an example of you can do to achieve your goal:
angular.module('limitToExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.serverResponse = {
"id": 1,
"value": "Rude",
"color": "red"
};
$scope.personalityFields = {
traveller_type: [{
"id": 1,
"value": "Rude",
"color": "red"
}, {
"id": 2,
"value": "Cordial",
"color": "yellow"
}, {
"id": 3,
"value": "Very Friendly",
"color": "green"
}],
}
}]);
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example103-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
</head>
<body ng-app="limitToExample">
<div ng-controller="ExampleController">
<select map-value name="traveller_type" class="full-width" ng-model="serverResponse" ng-options="item as item.value for item in personalityFields.traveller_type track by item.value">
</select>
</div>
</body>
</html>
This is one way of setting the default value, you can make it dynamic based on the response of your server (guess that is what you want?)
I am only replicating what #Pengyy describes in his answer, so feel free to accept his over mine.

angularjs: passing value to custom filter to enable it on dropdown click

I have a some data. By default all data should be shown up but when user click on some value in the drop-down then only the filter should start filtering the data.
To do so I am following the below approach.
My filter is like this
filter('myFilter', function() {
return function(data, userInput) {
var filteredArray = [];
// this show whole data
if (true) {/*want to insert enableFilter variable here*/
angular.forEach(data, function(dataobj, key) {
console.log(dataobj);
filteredArray.push(dataobj);
})
}
//this show filtered data
else {
angular.forEach(userInput, function(value, key) {
angular.forEach(data, function(dataobj, key) {
if (dataobj.type.indexOf(value) > -1 && filteredArray.indexOf(dataobj) == -1) {
filteredArray.push(dataobj);
}
})
});
}
return filteredArray;
}
});
To get the user click event I am using ng-change like this
<select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" ng-change=click() multiple>
<option value="classA">Class A</option>
<option value="classB">Class B</option>
<option value="classC">Class C</option>
<option value="classD">Class D</option>
<option value="classE">Class E</option>
Now how can I push the value (i.e. enableFilter) from controller to filter,(I also tried this - Passing arguments to angularjs filters but didn't work ) so that when user click on the drop down then only filter start filtering the data.
My controller is-
angular.module('myapp', [])
.controller('myController', ['$scope', function($scope) {
enableFilter = true;
$scope.enableFilter = true;
/*On user click*/
$scope.click = function() {
console.log("user click");
enableFilter = false;
console.log(enableFilter);
};
$scope.data = {
multipleSelect: []
};
//data
$scope.data = [{
"id": "1",
"type": ["classA", "classB", "classC"],
"name": "Name 1"
}, {
"id": "2",
"type": ["classB", "classC", "classE"],
"name": "Name 2"
}, {
"id": "3",
"type": ["classC"],
"name": "Name 3"
}, {
"id": "4",
"type": ["classD", "classC"],
"name": "Name 4"
}, {
"id": "5",
"type": ["classA", "classB", "classC", "classD", "classE"],
"name": "Name 5"
}];
}])
here is my plunker (http://plnkr.co/edit/QlSe8wYFdRBvK1uM6RY1?p=preview)
if (true) {/*want to insert enableFilter variable here*/
Change true to false for filters codde to work.
The way you wanted :
http://plnkr.co/edit/70jTmSFwtjQ4Nbnb7EVY?p=preview
I have passed a scope param to filter and initially it is set to true and when user selects from the drop down it gets set to false and filter starts applying.

Categories

Resources