Dynamically create parameter from array in jQuery - javascript

I'm using this plugin on my website, which works great. You can pass a parameter for state specific styles, it looks like this:
$('#map').usmap({
showLabels: false,
stateStyles: {
fill : '#ffffff',
stroke : '#4f4f4f',
'stroke-width' : 4,
},
stateHoverStyles: {
fill : '#ffffff'
},
stateSpecificStyles: {
'IN': {
fill : '#84b8e7'
},
'CA': {
fill : '#84b8e7'
},
'TX': {
fill : '#84b8e7'
}
},
stateSpecificHoverStyles: {
'IN': {
fill : '#0972ce'
},
'CA': {
fill : '#0972ce'
},
TX': {
fill : '#0972ce'
}
}
});
I would like to fill in those state styles dynamically from an array that looks like ["CA", "IN", "TX"]. Is this possible?

If you're just looking for a way to create an object that looks like that, this snippet will do it for you. Let us know more about what you have/need, and I can expand this.
var arr = ['CA', 'IN', 'TX'], // Your state vars
output = [];
arr.forEach(function(el) {
output[el] = {
fill: '#000000' // Could come from the same array, if needed
};
)};
console.log(output);

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.

Where to add and register the custom attributes in flot-pie chart js?

Although this question has answer at: Adding custom attributes to flot data
but I have tried every possible way but my custom attributes are not showing on click event.
So far I tried this:
html:
<div id="audit_status" class="chart"></div>
JS:
var audit_status = [
{label: "Pending", data: 2, location_value="Majiwada,Pune"},
{ label: "Ongoing", data: 1 location_value="Mumbai"},
];
var options = {
series: {
pie: {
show: true,
label: {
show: true,
radius: 120,
formatter: function (label, series) {
return '<div style="border:1px solid grey;font-size:8pt;text-align:center;padding:5px;color:white;background-color: #90bdce;">' +
label + ' : ' +
series.data[0][1] +
' ('+Math.round(series.percent)+' %)</div>';
},
background: {
opacity: 0.8,
color: '#000'
}
}
}
},
legend: {
show: true
},
grid: {
hoverable: true,
clickable: true
}
};
$("#audit_status").bind("plotclick", function(event, pos, obj) {
console.log(obj);
//alert(obj.series.value);
if (obj) {
alert(obj.series.location_value);
}
});
$(document).ready(function () {
$.plot($("#audit_status"), audit_status, options);
});
The problem is: whenever I click the pie segment I want to alert "location_value"
but i am getting [Object Object]
I see two issues with the code as it is now. First, the audit_status JSON object isn't quite defined right. The location_value properties need to use colons, not equal signs:
var audit_status = [
{ label: "Pending", data: 2, location_value: "Majiwada,Pune" },
{ label: "Ongoing", data: 1, location_value: "Mumbai" }
];
Second, in your plotclick function, the extra properties defined in your data object don't make it over to the series object passed into the callback. You need to reference the original data object, using the obj.seriesIndex provided to the callback. This JSFiddle provides an example of the code below.
var data = [{
label: "Yes",
data: 50,
location_value: 'Majiwada,Pune'
}, {
label: "No",
data: 150,
location_value: 'Mumbai'
}];
// plot initialization code here
$("#pie").bind("plotclick", function(event, pos, obj) {
if (obj) {
// use the obj.seriesIndex to grab the original data object,
// then you can use any property you defined on that object
alert(data[obj.seriesIndex].location_value);
}
});

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.

How do you influence position of connectors in a heirarchical Kendo UI Diagram

I am building an organisation chart using Kendo UI's diagramming component
I do not want the user to be able to edit the diagram as it is a read-only representation of positions they have entered previously, however I do want to display the diagram in a particular way.
The layout type I am using is tree with subtype of down. I am using the HeirarchicalDataSource as the dataSource
The default way the diagram is drawn looks like this:
However, my boss needs it to look like this:
So the parent nodes have all child nodes coming from the bottom connector.
I see no way to programmatically influence this. Please help.
Switching editing off is easy, just pass to your options editable: false. To have the layout similar to what you posted, play with two variables: horizontalSeparation, verticalSeparation under layout
http://dojo.telerik.com/uNOVa/2
function createDiagram() {
$("#diagram").kendoDiagram({
editable: false,
dataSource: {
data: diagramNodes(),
schema: {
model: {
children: "items"
}
}
},
layout: {
type: "tree",
subtype: "down",
horizontalSeparation: 60,
verticalSeparation: 40
},
shapeDefaults: {
width: 40,
height: 40
}
});
}
function diagramNodes() {
var root = { name: "0", items: [] };
addNodes(root, [3, 2, 2]);
return [root];
}
function addNodes(root, levels) {
if (levels.length > 0) {
for (var i = 0; i < levels[0]; i++) {
var node = { name: "0", items: [] };
root.items.push(node);
addNodes(node, levels.slice(1));
}
}
}
$(document).ready(function() {
$("#subtype").change(function() {
$("#diagram").getKendoDiagram().layout({
subtype: $(this).val(),
type: "tree",
horizontalSeparation: 30,
verticalSeparation: 20
});
});
});
$(document).ready(createDiagram);
$(document).bind("kendo:skinChange", createDiagram);
There is another type of rendering connections with:
connectionDefaults: {
type: "polyline"
}
You can check it out here: http://dojo.telerik.com/uNOVa/3
You can also fix your connections with an array:
connections
An example is here:
example

Javascript: how can I populate an array of property values dynamically?

I have an array of values, which I want to insert into a property of an object, but I'm not sure how. Here's my object. The property is called "values" (located at the very bottom), and as you can see, I'm trying to insert a dynamic list of data (called "result") into it:
var myConfig = {
globals: {
fontFamily: "Roboto"
},
type: "bar",
backgroundColor: "#f4f2f2",
plotarea: {
backgroundColor: "#fff"
},
scaleX: {
lineColor: "#7d7d7d",
tick: {
lineColor: "#7d7d7d"
},
guide: {
visible: false
},
values: [result[0]["Heading"], result[1]["Heading"], result[2]["Heading"], ...],
}};
Is there any way I can set this up to dynamically place this result["Heading"] data into my "values" property?
Thanks
So, assuming results is an array of objects that have the Heading property, you can get an array of only those, using the map function, like this:
values: result.map(function(item){ return item.Heading; })
map is a new-ish function, defined in ECMAScript 5.1, but all major browsers support it. Basically, for every item in the array, it will execute the provided selector function, and return the result. So, you're starting with an array of objects having a Heading property, and ending up with an array of the Heading property values themselves.
Make another function to do that.
It's an Array.
You should traverse it at least once.
function getHeading( arr ) {
var aa = [];
for( var i = 0, size = arr.length ; i < size ; i++ ) {
aa.push( arr[i].Heading );
}
return aa;
}
var myConfig = {
globals: {
fontFamily: "Roboto"
},
type: "bar",
backgroundColor: "#f4f2f2",
plotarea: {
backgroundColor: "#fff"
},
scaleX: {
lineColor: "#7d7d7d",
tick: {
lineColor: "#7d7d7d"
},
guide: {
visible: false
},
values: getHeading( result ),
}};

Categories

Resources