How can i access to object elements in javascript? - javascript

I'am using the jQuery Gantt api, and I want to access to certain elements, but I don't know how.
$(function() {
"use strict";
//var obj = JSON.parse($(".gantt").gantt);
$(".gantt").gantt({
source: [{
name: "Sprint 0",
desc: "Analysis",
values: [{
from: "/Date(1320192000000)/",
to: "/Date(1322401600000)/",
label: "Requirement Gathering",
customClass: "ganttRed"
}]
}],
navigate: "scroll",
scale: "weeks",
maxScale: "months",
minScale: "days",
itemsPerPage: 10,
onItemClick: function(data) {
alert("Item clicked - show some details");
},
onAddClick: function(dt, rowId) {
alert("Empty space clicked - add an item!");
},
onRender: function() {
if (window.console && typeof console.log === "function") {
console.log("chart rendered");
}
}
});
//alert("OK");
//var parsedData = JSON.parse();
//alert($(".gantt").gantt.source);
$(".gantt").popover({
selector: ".bar",
title: "I'm a popover",
content: "And I'm the content of said popover.",
trigger: "hover"
});
prettyPrint();
});
I found this ape with static example, but am trying to draw my own chart by changing content of element source.
so can some tell me how can i get the element source from the gantt object.

Do you expecting this?
To access gantt elements through object try like this.
var ganttObj = $(".gantt").data("gantt");
Or try to create instance for your gantt like this.
var ganttObj = $(".gantt").gantt("instance");
ganttObj.model.maxScale = "years" //To change `maxScale` property values dynamically
Or you can also directly access your elements like this.
For eg: To change maxScale value from months to years, you can use like below.
$(".gantt").gantt({ maxScale: "years" });
Please let me know if this helps you.

Based on your example, you could simply move the source data into a variable so you can reference it later:
var ganttSource = [{
name: "Sprint 0",
desc: "Analysis",
values: [{
from: "/Date(1320192000000)/",
to: "/Date(1322401600000)/",
label: "Requirement Gathering",
customClass: "ganttRed"
}]
}];
$(".gantt").gantt({
source: ganttSource,
...
});
console.log(ganttSource);

Related

Select2 and Jexcel add new option to dropdown

I have this code of Jexel with Select2 where I load the default values for each jexcel row from an array and use select2 for the dropdown:
https://jsfiddle.net/ktumw528/
However I wish to know how can I populate the options from select2 with the values from var data?
Also how can I add new country to the select2 dropdown if not found when typing.
var data = [
['Spain'],
['France'],
['Germany'],
];
var customDropDown1 = {
// Methods
closeEditor : function(cell, save) {
// Get value
var txt = $(cell).find('.editor').val();
// Set visual value
$(cell).html(txt);
// Close edition
$(cell).removeClass('edition');
// Save history
return txt;
},
openEditor : function(cell) {
// Get current content
var currentValue = $(cell).text();
// Create the editor
var editor = document.createElement('select');
$(cell).html(editor);
$(editor).prop('class', 'editor');
$(editor).html('<option>Brazil</option><option>Canada</option>')
$(editor).val(currentValue);
// Create the instance of the plugin
$(editor).select2().on('select2-blur', function() {
$('#' + $.fn.jexcel.current).jexcel('closeEditor', $(cell), true);
});
},
getValue : function(cell) {
return $(cell).text();
},
setValue : function(cell, value) {
$(cell).html(value);
return true;
}
}
$('#my').jexcel({
data:data,
columns: [ { editor:customDropDown1 } ],
colHeaders: ['Country'],
colWidths: [ 300 ]
});
Any tips are welcomed :) thanks a lot!
I think you can use last version of JExcel (v4). You will have more options and more option editor.
With this new version, you can create editor with set custom value. And you have an option for dropdown for add new item
https://bossanova.uk/jexcel/v4/examples/dropdown-and-autocomplete
and this documentation : https://bossanova.uk/jsuites/dropdown-and-autocomplete/new-options
Example :
<script>
var data5 = [
[1, 'Beatles'],
[2, 'Beatles'],
[3, 'Beatles'],
[4, 'Beatles'],
];
jexcel(document.getElementById('spreadsheet5'), {
data: data5,
columns: [
{
type: 'dropdown',
title: 'Name',
width: '300px',
source: [
{ id:'1', name:'Paul' },
{ id:'2', name:'Ringo' },
{ id:'3', name:'George' },
{ id:'4', name:'John' },
],
options: { newOptions: true } // Option for add new options
},
{
type:'dropdown',
title:'Band',
width:'200px',
source: ['Beatles'],
},
],
});
<script>
otherwise if you want keep v2, i suggest use external source on var, and add new item on this variable. Because the editor is created only on open cell.

ChartJS dynamically adding values with jQuery array

I am trying to populate a piechart in ChartJS dynamically using data from a jQuery/AJAX query.
The only thing I am struggling with is creating the data in a format that chartJS understands. This is the required format:
var dynamicData = [
{ label: "One", value: 23 },
{ label: "Two", value: 33 },
{ label: "Three", value: 43 },
{ label: "Four", value: 53 },
]
When I try to create it, I get double quotes "" around each set of data. I know it is a simple mistake but I can't figure it out. This is how I am creating the data (partial jQuery code):
.success(function(response) {
if(!response.errors && response.result) {
var doughnutData = [];
$.each(response.result, function( index, value) {
doughnutData.push('{ label: "'+value[0]+'", value: '+value[2]+',color:"#F7464A" }');
});
console.log(doughnutData);
var doughnutOptions = {
segmentShowStroke : true,
segmentStrokeColor : "#fff",
segmentStrokeWidth : 2,
percentageInnerCutout : 50,
animation : true,
animationSteps : 100,
animationEasing : "easeOutBounce",
animateRotate : true,
animateScale : true,
onAnimationComplete : null
}
var ctx = document.getElementById("chart3").getContext("2d");
var mydoughnutChart = new Chart(ctx).Doughnut(dynamicData, doughnutOptions);
} else {
alert("error");
}
The console shows:
["{ label: "17x1p14e6662", value: 16,color:"#F7464A" }", "{ label: "8734hjgfd784ew", value: 8,color:"#F7464A" }"]
What am I doing wrong?
The console is outputting the object as a string because you are pushing a string to the var doughnutData, you are doing this wrapping the object in quotes and concatenating the values to the string therefor treating the argument passed to the push method as a string type.
The proper way to use the push method to add an object to an array would be like this.
array.push({property:'string', property:2})
Meaning your code should look like this.
doughnutData.push({ label:value[0], value:value[2],color:"#F7464A" });
Here is a link on how the push method works on an array and Here is another link to javascript objects
Another thing is when you are creating the chart your are passing the var dynamicData instead of your var doughnutData.

stockChart is not defined(…)

I would like to use highstock but I can't seem to get it to work... my code:
$(function () {
$.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=aapl-v.json&callback=?', function (data) {
// create the chart
var options = {
chart: {
alignTicks: false,
renderTo: 'container'
},
rangeSelector: {
selected: 1
},
title: {
text: 'AAPL Stock Volume'
},
series: [{
type: 'column',
name: 'AAPL Stock Volume',
data: data,
dataGrouping: {
units: [[
'week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]
]]
}
}]
};
});
var chart = new stockChart(options);
});
The browser doesn't display anything and if I go to look at the error;
stockChart is not defined(…)
I have also tried the code from this JSFiddle, but it didn't work either. So i tried to use the options, but this doesn't work as well.. Could someone help me out?
You need to add the HighStock JavaScript library before your initialisation script:
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
Alternatively, as given in the fiddle, you can use this to initialise:
chart = Highcharts.stockChart('container', options);
You are calling the function stockChart as a constructor function using the keyword "new". The reason you get a "is not defined error" is because in your code, that stockChart function is nowhere to be found!
To create one write
var stockChart = function(opt){
this.someproperty = "hello there im a stockchart"
};
With this function, you can then "new" the stockChart
var my_stockchart = new stockChart();
Now you can use your newly formed my_stockchart object and call its methods. Try it in your console.
my_stockchart.someproperty
returns => "hello there im a stockchart"
Now if you want the quick and dirty answer, I guess other people got you covered. So basically what it comes down to is that you're calling a function that is not yet defined in your code. Hope this helps.
Use Highcharts.stockChart or new Highcharts.StockChart.
Also, you create a new chart before the data is received (get.json works asynchronously) and you try to access options which is defined in a different scope.
$(function () {
$.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=aapl-v.json&callback=?', function (data) {
// create the chart
var options = {
chart: {
alignTicks: false,
renderTo: 'container'
},
rangeSelector: {
selected: 1
},
title: {
text: 'AAPL Stock Volume'
},
series: [{
type: 'column',
name: 'AAPL Stock Volume',
data: data,
dataGrouping: {
units: [[
'week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]
]]
}
}]
};
var chart = Highcharts.stockChart(options); // alternatively new Highcharts.StockChart(options);
});
});

Getting JSON from Google for Highmaps

I'm pretty rusty with JavaScript, so I'm hoping someone can help me out. I'm working with Highmaps and would like to link the map to data in a Google Spreadsheet. (It's a U.S. map of counties which will be updated regularly, so having it all in the script itself is a little unwieldy.)
This is what my code looks like now:
<script type="text/javascript">
var example = 'us-counties',
theme = 'default';
(function($) { // encapsulate jQuery
$(function() {
var data = [{
"code": "us-al-001",
"name": "Autauga County, AL",
"value": 0
},
…
{
"code": "us-pr-153",
"name": "Yauco Municipio, PR",
"value": 0
}],
countiesMap = Highcharts.geojson(Highcharts.maps['countries/us/us-all-all']),
lines = Highcharts.geojson(Highcharts.maps['countries/us/us-all-all'], 'mapline'),
options;
// Add state acronym for tooltip
Highcharts.each(countiesMap, function(mapPoint) {
mapPoint.name = mapPoint.name + ' County, ' + mapPoint.properties['hc-key'].substr(3, 2);
});
series: [{
name: 'County',
mapData: countiesMap,
data: data,
joinBy: ['hc-key', 'code'],
tooltip: {
enabled: true,
positioner: function () {
return { x: 0, y: 250 };
},
pointFormat: '{point.name}',
borders: 0.5
},
borderWidth: 0.5
}, {
type: 'mapline',
name: 'State borders',
data: [lines[0]],
color: 'white'
}, {
type: 'mapline',
name: 'Separator',
data: [lines[1]],
color: 'gray'
}]
};
// Instanciate the map
$('#container').highcharts('Map', options);
});
$(document).ready(function() {
$("#view-menu").click(function(e) {
$("#wrap").toggleClass("toggled");
});
$("#sidebar-close").click(function(e) {
$("#wrap").removeClass("toggled");
});
});
})(jQuery);
</script>
Of course, since there's over 3,200 counties, I'd rather store that data elsewhere and pull it into the var data = [] string, but I'm not sure how to do that.
Any help would be appreciated.
Although this isn't something I've done, it looks like this should be relatively straightforward to do (although nothing is as simple as it looks of course).
There is an API for Google Sheets (https://developers.google.com/google-apps/spreadsheets/) and you can Google examples of how to retrieve data - this one looks clear (https://developers.google.com/gdata/docs/json) although it does point out that there are newer versions of some of the relevant APIs.
If you pull in the JSON data from the Google Sheet you then just need to put the values into the 'value' element of your data variable. You could do all of that within your main function or do it separately and pass it to your function as a parameter.

YUI 2 Populate Select with JSON

Really simple question but I can't find an answer. I know how to do this in regular javascript and I know how to do this in jquery. Right now if I have this:
var states = [{"name":"alaska","id":1},{"name":"alabama","id":2];
Is there an YUI based method to push that into a select box, to set the selected item, to get the selected item back? If so, where's the online example? If not I'll just use javascript.
Yes, there is. You can do something like this:
var buttonMenu = [
{ text: "Alaska", value: 1, onclick: { fn: onStateClick } },
{ text: "Alabama", value: 2, onclick: { fn: onStateClick } },
...];
.. and then use this in a YUI menu button configuration:
var statesButton = new YAHOO.widget.Button({ type: "menu", label: "Alabama", name: "mymenubutton", menu: buttonMenu, container: containerElement });
More details on the YUI button example page.
Hope that helps.

Categories

Resources