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"
};
Related
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);
}
I have this JSON response:
[
{storeWebsites=[
{website_id=1.0, name=Default Store View},
{website_id=0.0, name=Admin}
]},
{storeGroups=[
{website_id=0.0, name=Default, id=0.0},
{website_id=1.0, name=Main Website Store, id=1.0}
]},
{storeViews=[
{website_id=1.0, name=Default Store View, code=default, id=1.0},
{website_id=0.0, name=Admin, code=admin, id=0.0}
]}
]
I would like to group the "website_id" and append the "storeViews.name".
I'm trying to work with the script below but I'm not able to push the values in var group:
var groups = {};
// .... code to push the values in var groups
$.each(groups, function(key, groups) {
var $group1 = $("<optgroup>").attr("label", " " + groups.storeWebsites);
var $group2 = $("<optgroup>").attr("label", " " + groups.storeGroups);
groups.storeViews.forEach(function(el) {
$group2.append(new Option(el.name, el.code));
});
$('#provider-accounts').append($group1, $group2);
});
}
So my "id=provider-accounts" should be populated like below:
<optgroup label="Default Store View"></optgroup>
<optgroup label="Main Website Store">
<option code="default">Default Store View</option>
</optgroup>
<optgroup label="Admin"></optgroup>
<optgroup label="Default">
<option code="admin">Admin</option>
</optgroup>
Any help?
I think you have the following groups swapped:
<optgroup label="Default">
<optgroup label="Main Website Store">
Anyways, you could destructure your sites, groups, and views and keep track of their indices while looping over one of them.
const main = () => {
const [ { storeWebsites }, { storeGroups }, { storeViews }] = json;
$('#provider-accounts').append(storeWebsites.flatMap((site, index) => {
const
group = storeGroups[index],
view = storeViews[index];
return [
$('<optgroup>', { label: site.name }),
$('<optgroup>', { label: group.name })
.append($('<option>', { code: view.code, text: view.name }))
];
}));
};
const json = [{
"storeWebsites": [{
"website_id": 1.0,
"name": "Default Store View"
}, {
"website_id": 0.0,
"name": "Admin"
}]
}, {
"storeGroups": [{
"website_id": 0.0,
"name": "Default",
"id": 0.0
}, {
"website_id": 1.0,
"name": "Main Website Store",
"id": 1.0
}]
}, {
"storeViews": [{
"website_id": 1.0,
"name": "Default Store View",
"code": "default",
"id": 1.0
}, {
"website_id": 0.0,
"name": "Admin",
"code": "admin",
"id": 0.0
}]
}];
main();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="provider-accounts">
<!--
<optgroup label="Default Store View"></optgroup>
<optgroup label="Default">
<option code="default">Default Store View</option>
</optgroup>
<optgroup label="Admin"></optgroup>
<optgroup label="Main Website Store">
<option code="admin">Admin</option>
</optgroup>
-->
</select>
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>
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>
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;
}
})
}