I'm using noUiSlider and followed the tutorial how to create custom formatting:
noUiSlider.create(sliderFormat, {
start: [ 20 ],
step: 10,
range: {
'min': [ 0 ],
'max': [ 599 ]
},
format: {
to: function ( value ) {
return Math.round(value/60) + ':' + Math.round(value%60);
},
from: function ( value ) {
return value;
}
}
});
When I call
mySlider.get()
it returns a value like 1:10, which is the formatted value. I would like to get the raw value (like 70 in this example), how is that possible?
As Vaibhav Kumar suggestet, I used the update function to read the raw value:
slider.noUiSlider.on('update', function(values,handle,unencoded){
// unencoded contains the raw value
});
Related
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.
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 ),
}};
I want that the tooltip on my slider only shows integers like "130" and not "130.00".
I just dont know where i could start.
Here is my code:
$( document ).ready(function() {
var groesseslider = document.getElementById('slider-tooltip');
noUiSlider.create(groesseslider, {
start: [ 145 ],
step: 1,
range: {
'min': 100,
'max': 250
}
});
});
$( document ).ready(function() {
var groesseslider = document.getElementById('slider-tooltip');
var tipHandles = groesseslider.getElementsByClassName('noUi-handle'),
tooltips = [];
// Add divs to the slider handles.
for ( var i = 0; i < tipHandles.length; i++ ){
tooltips[i] = document.createElement('div');
tipHandles[i].appendChild(tooltips[i]);
}
// When the slider changes, write the value to the tooltips.
groesseslider.noUiSlider.on('update', function( values, handle ){
tooltips[handle].innerHTML = values[handle];
});
});
My JS Code:
http://jsfiddle.net/miiauwz/66a5ahm0/
This can work..
var sliderFormat = document.getElementById('slider-format');
noUiSlider.create(sliderFormat, {
start: [ 20 ],
...
format: {
from: function(value) {
return parseInt(value);
},
to: function(value) {
return parseInt(value);
}
}
});
You can either try using the unencoded value like described in noUISlider's documentation about events and their binding
slider.noUiSlider.on("update", function(values, handle, unencoded ) {
// values: Current slider values;
// handle: Handle that caused the event;
// unencoded: Slider values without formatting;
});
or another possibility would be using the format option on slider creation (but haven't tried it myself yet):
noUiSlider.create(slider, {
start: [ 20000 ],
...
format: wNumb({
decimals: 0, // default is 2
thousand: '.', // thousand delimiter
postfix: ' (US $)', // gets appended after the number
})
});
The drawback is you have to download the wNumb-Library separately from here: http://refreshless.com/wnumb/.
Another way without wNumb
After having another look at the examples from noUISlider, I found this way for manually formatting (at the bottom of the page):
var sliderFormat = document.getElementById('slider-format');
noUiSlider.create(sliderFormat, {
start: [ 20 ],
...
format: {
to: function ( value ) {
return value + ',-';
},
from: function ( value ) {
return value.replace(',-', '');
}
}
});
If you don't think you'll ever need to have decimal places on your site, you can search the jquery.nouislider.min.js file for toFixed(2) and replace with toFixed(0).
I you don't want to use wNumb - library , this method might work.
This will give you value without decimals.
Hope this helps.
value.split('.')[0]
Possible way without using any other library. If we want to show only integers there is no need to use additional libraries. Assuming that in the html code there is the element 'slider-fee'.
<div id="slider-fee"></div>
Let's say that we want to give the possibility to choose a range of hours in a day. Something like 7h-19h or 8h-20h and in the tooltip we want to display the integer only.
dragTapSlider = document.getElementById('slider-fee');
// number of decimal places
decimals = 0;
// format object
numberFormat = {
// 'to' the formatted value. Receives a number.
to: function (value) {
return value.toFixed(decimals);
},
// 'from' the formatted value.
// Receives a string, should return a number.
from: function (value) {
return Number(value);;
}
};
noUiSlider.create(dragTapSlider, {
start: [8, 20],
connect: [false, true, false],
step: 1,
behaviour: 'drag',
tooltips: [true, true],
range: {
'min': 1,
'max': 24
},
format: numberFormat
});
noUiSlider - Integer Format
Example for money range
dragTapSlider = document.getElementById('slider-fee');
decimals = 2;
suffix = '€';
numberFormat = {
// 'to' Format the value to currency.
to: function (value) {
return value.toFixed(decimals) + ' ' + suffix;
},
// 'from' Convert currency value to number.
// Receives a string, should return a number.
from: function (value) {
return Number(value.replace(' ' + suffix));
}
};
noUiSlider.create(dragTapSlider, {
start: [25, 40],
connect: [false, true, false],
step: 0.5,
behaviour: 'drag',
tooltips: [true, true],
range: {
'min': 20,
'max': 50
},
format: numberFormat
});
noUiSlider - Currency Format
Figured I'd provide an answer in case someone else comes looking for this. Simply add the following as an option to the noUiSlider creation:
tooltips: [ wNumb({ decimals: 0 }), wNumb({ decimals: 0 }) ],
The following code will create the slider you need with the noUiSlider tooltip displaying only the integer value with no decimal points:
$( document ).ready(function() {
var groesseslider = document.getElementById('slider-tooltip');
noUiSlider.create(groesseslider, {
start: [ 145 ],
step: 1,
tooltips: [ wNumb({ decimals: 0 }), wNumb({ decimals: 0 }) ],
range: {
'min': 100,
'max': 250
}
});
Just use Math for this instead of the library.
Math.round(value)
var skipSlider = document.getElementById('price');
noUiSlider.create(skipSlider, {
start: [47000, 247000],
connect: true,
behaviour: 'drag',
step: 1,
range: {
'min': [47000],
'max': [247000]
},
});
var skipValues = [
document.getElementById('min-price'),
document.getElementById('max-price')
];
skipSlider.noUiSlider.on('update', function (values, handle, unencoded) {
skipValues[handle].innerHTML = unencoded[handle];
});
React example with no external library:
<Nouislider
range={{ min: 0, max: 5 }}
tooltips={true}
step={1}
start={[0, 5]}
connect
format={{
from: (value) => {
return parseInt(value);
},
to: (value) => {
return parseInt(value);
}
}}
onSlide={onUpdate}
/>
I would like to have the y-axis only with the min/max values of my data.
I tried to use the d3 directive but without results.
I had a look at google but I didn't find an answer to achieve this behaviour.
Below the code:
$.getJSON('assets/json/chartc3.json', function(data)
{
scene=data;
var chart = c3.generate({
bindto: '#chartc3',
data:
{
json: scene,
keys:
{
x: 'round',
value: ['Marketable', 'Total Requested Capacity', 'Your Bid'],
},
types: {
Marketable: 'area'
},
colors: {
Marketable: '#A09FA2',
'Total Requested Capacity': '#272E80',
'Your Bid': '#8EBF60'
}
},
axis:
{
x: {
tick:
{
culling:
{
max: 10
}
},
type: 'category'
},
y:
{
min: 0,
padding : {
bottom : 0
},
tick:
{
values: [[0], [***d3.max(scene)]***],
format: function (d) { return d3.format(',f')(d) +' kWh/h' }
//or format: function (d) { return '$' + d; }
}
}
}.........
How could I achieve the result described above ? d3.max(scene) returns NaN.
Well the problem is scene is not an array its a json object.
var k = d3.max([1,5,2])
k will be 5
so you will need to pass an array of elements which constitute your y ordinals.
you need to use
d3.max(arr, function(d){return numberic value});
or
var arr = scene.map(function(d){return ...the number value..})
y:{
min:d3.min(arr),
max:d3.max(arr)
},
the function depends on the array element of your data.
I used a little function to calculate the max by myself.
var maxs=0;
for (var j=0; j<scene.length; j++) {
var maxtemp=Math.max(scene[j].Marketable, scene[j]['Your Bid'], scene[j]['Total Requested Capacity']);
maxs=Math.max(maxs, maxtemp);
}
I need some advice (help) on the most efficient way to implement a form that incorporates a range slider to set a value (in this case annual mileage), then takes that value and multiplies it by a set constant (0.05) and plugs the result into a second form field with a unit of British Pounds (£) and an accuracy of 2 decimal places rounded as appropriate. I am using a slider called No UI Slider (http://refreshless.com/nouislider/) and have set up the basic elements here:
$("#sliderAnnualMileage").noUiSlider({
start: [ 0 ],
step: 1000,
range: {
'min': [ 0 ],
'max': [ 120000 ]
},
connect: "lower",
serialization: {
lower: [
$.Link({
target: $("#mileage"),
format: {
thousand: ',',
decimals: 0,
postfix: ' miles'
}
})
]
}
});
Here is a partially working JS Fiddle: http://jsfiddle.net/highlander/jMA98/1/
Any insight or experience you have would be much appreciated.
You can set another $.Link to the second input box, with a formatting function:
lower: [
// your one
// then this:
$.Link({
target: $("#annualSavings"),
method: function (val) {
$(this).val("£" + (val * 0.05).toFixed(2));
}
})
]
This is the result: http://jsfiddle.net/jMA98/3/
For whatever reason your slider resets the value.
http://jsfiddle.net/jMA98/2/
$('#mileage').on('change',function(){
console.log($(this).val().replace(' miles',''));
$('#annualSavings').val($(this).val().replace(' miles','')*0.05);
});
Other than that this works.