Using Variable Within JavaScript Object Literal - javascript

Basically, I'm having trouble getting information from an input box and using that variable within an object literal.
Here is my code:
$("document").ready(function() {
function updateEvent(){
render();
}
function render() {
//get values from input
var gallons = $("#gallons").val();
var electricity = $("#electricity").val();
var energy = $("#energy").val();
var figure = new Highcharts.Chart({
series: [{
name: 'Throttle',
data: [0, 0, 30 , 0, energy, 30, 0, 0] //Variables will not work in here, no specific error but data doesn't show
}, {
name: 'Power',
data: [30, 30 , 30, 30, 30, 30, 30, 30]
}]
});
I've tried embedding a function and doing other tricks but nothing has worked, I could be doing it wrong, I'm not sure. Is there any way to use a variable within an object literal without completely re-coding the structure.
Any help would be greatly appreciated.

How to get a value from an input box and use that value within an object literal?
function doStuff(){
var realIncome = document.getElementById("income").value;
var objLit= { realIncome: realIncome,
desiredIncome: realIncome * 4 };
console.log(objLit);
document.getElementById("out").innerText =
objLit.realIncome + " " + objLit.desiredIncome;
}
And the HTML
Big Number
<input id="income" name="income" type="number"
placeholder="please enter your desired income">
<button name="calculate" onclick="doStuff()">click me </button>​
Your income <span id="out"></span><br />
Please take a look at my demo code: http://jsfiddle.net/mppAM/2/

Related

Colouring markers based on value of another column - plotly.js

I'm currently writing a reporting dashboard for work and thanks to some changes in what is supported, my fancy and dynamic RShiny app is a no go so i'm trying to port it all over to javascript. I know almost no js, having written everything i know in python and R, and it is causing a significant head ache.
Problem:
I'm importing a csv and attempting to have dynamically produced graphs show a variety of things, coloured by a particular columns values.
So to keep it simple, (the real csv has almost twenty columns at this point and a few hundred rows of data) lets say i have:
#X.sample_id, key, project_type, manual_interventions
BulBa, 152, AAA, 12000
CharZard, 100, AAB, 5000
PikaChu, 117, AAA, 10
SquirTle, 090, AAB, 1000
Plotting X.sample_id as the X-axis, manual_interventions as Y and most importantly I need them to be coloured by project_type. Now i know this as easy as anything in python and R, the problem is that I don't want to produce a few dozen graphs to show variations of the same thing (there will be options for y-axis to be a fair few different things), especially when this can be done dynamically.
So far I have written:
<select onchange="selectedY()" style="right: 10px; top: 20px;" id="dataBtn" title="Choose data">
<option value="">Choose options</option>
<option value="X.sample_id">TolID</option>
<option value="key">GRIT Key</option>
<option value="manual_interventions">Manual Interventions</option>
</select>
<div class="card-body" id="chart"></div>
<script>
var data = [];
var layout= {title: 'Graph', 'xaxis': {'title': 'X-axis'},
autosize: true,
width: 500,
height: 500};
var allRows = null
Plotly.d3.csv('assets/data/pulled_data_sorted.csv', function(err, data){
allRows = data
});
Plotly.plot("chart", data, layout, type="scatter", mode="markers");
function selectedY() {
var axisValue = $("#dataBtn :selected").val();
var x_row = [], y_data = [];
for (var i=0; i<allRows.length; i++) {
xrow = i;
row = allRows[i];
x_row.push(xrow);
y_data.push(+row[axisValue]);
var dataRow = {
x: x_row,
y: y_data,
mode: 'markers',
type: 'scatter',
line: {
color: '#62B5E5',
width: 2
}
};
}
layout['yaxis'] = {'title': {'text': axisValue}}
Plotly.restyle('chart', 'y', [[]]);
Plotly.plot("chart", [dataRow], layout, type="scatter", mode="markers");
}
</script>
This produces:
Which is pretty far from the publication level it needs to be.
Admittedly, this was adapted from another persons work as i've found it difficult getting to grips with this, and i think there isn't much information showing any particular in-depth use of csv's and plotly (maybe i'm not looking in the right place, i don't know).
So in the end I have no properly formatted X axis, I need to add an option to change the column of data X-axis uses, and no colour by project_type and I can't understand how to go further.
Any help is much appreciated.
Thanks.
I have fixed this now, i was relying on this working much like Python or R where colour is essentially figured out by the script rather than being explicitly given to it.
I'm aware this is still rough and i have alot to learn but i'm posting this in case it helps any future prospective js student.
<select onchange="selected()" style="right: 10px; top: 20px;" id="dataBtn" title="Choose data">
<option value="#sample_id">Tol</option>
<option value="key">Key</option>
<option value="manual_interventions">Manual Interventions</option>
</select>
<select onchange="selected()" style="right: 10px; top: 20px;" id="dataBtn2" title="Choose data">
<option value="manual_interventions">Manual Interventions</option>
<option value="length change">Percentage Genome Length Change</option>
</select>
<select onchange="selected()" style="right: 10px; top: 20px;" id="dataBtn3" title="Choose data">
<option value="project_type">Project Type</option>
<option value="'prefix">Clade Prefix</option>
</select>
<script>
function selected() {
makeplot()
}
function makeplot() {
Plotly.d3.csv('CSV FILE',
function(data){ processData(data) });
}
var layout = {
autosize: true,
width: 800,
height: 800,
xaxis:
{title: {text: "ID"}},
yaxis:
{title: {text: "manual_interactions"}}
}
function processData(allRows) {
console.log(allRows);
var x = [], y = [], colour = [];
var xaxis = $("#dataBtn").val()
var yaxis = $("#dataBtn2").val()
var colaxis = $("#dataBtn3").val()
for (var i=0; i<allRows.length; i++) {
row = allRows[i];
x.push( row[xaxis] );
y.push( row[yaxis] );
colour.push( getColour(row[colaxis]) );
}
console.log( 'X',x, 'Y',y, 'colour', colour);
makePlotly( x, y, colour, layout );
}
function rand_colour () {
var r = Math.random()*255;
var g = Math.random()*255;
var b = Math.random()*255;
return 'rgb('+r+','+g+','+b+')'
}
var colour_map = {}
function getColour(project) {
console.log(colour_map)
if (project in colour_map) {return colour_map[project]}
colour_map[project] = rand_colour();
console.log(colour_map[project]);
return colour_map[project]
}
function makePlotly( x, y, colour, layout){
var traces = [{
x: x,
y: y,
type: "scatter",
mode: "markers",
marker: {
color: colour,
width: 2
}
}];
Plotly.react('chart', traces, layout, {displayModeBar: true});
}
makeplot();
</script>
This has resulted in the following being produced, it's not perfect but it is definitely much closer to what i need than before. It is coloured by the number of projects in use.

How do I know which cell is highlighted in jexcell javascript library?

I want to merge the cells marked with jexcel. I don't know how to do that. More specifically, I want to merge cells into a dynamic state and write them into merged cells in MySQL. How to do it
<div id="example"></div>
<script>
var data = [
['', 'Ford', 'Tesla', 'Toyota', 'Honda'],
['2017', 10, 11, 12, 13],
['2018', 20, 11, 14, 13],
['2019', 30, 15, 12, 13]
];
var container = document.getElementById('example');
var hot = new Handsontable(container, {
data: data,
rowHeaders: true,
colHeaders: true,
filters: true,
dropdownMenu: true,
contextMenu: true
});
</script>
Your Question is not clear but I'll try to answer it to the best of my ability.
if I ignore the example you provided and focus on jExcel, we can merge cells using setMerge and for that we need to know:
the address of the first cell
the numbers of selected rows
numbers of selected columns
we can extract this info from:
$("#spreadsheet").jexcel("getSelectedRows", true);
$("#spreadsheet").jexcel("getSelectedColumns", true);
in theory this alone should work, but jExcel deselects cells when it loses focus (ie when user clicks a button) that's why I used a workarround to store the selection of cells in an object, and later used that object to merge cells.
HTML:
<div id="spreadsheet"></div>
<br>
<input id="myB" type="button" value="Merge Selected" />
Javascript:
var mySlection = {};
var options = {
minDimensions: [10, 10],
onselection: storeSelection
};
$(document).ready(function() {
var mySpreadsheet = $("#spreadsheet").jexcel(options);
$("#myB").click(function() {
//Merge Cells using the stored selection
$("#spreadsheet").jexcel("setMerge", mySlection.firstcell, mySlection.colspan, mySlection.rowspan)
/*
you may now store the following values to your MySQL
mySlection.firstcell
mySlection.colspan
mySlection.rowspan
*/
});
});
function storeSelection() {
var sRows = $("#spreadsheet").jexcel("getSelectedRows", true);
var sCols = $("#spreadsheet").jexcel("getSelectedColumns", true);
mySlection.firstcell = [sCols[0], sRows[0]];
mySlection.colspan = sCols.length;
mySlection.rowspan = sRows.length;
}
Requirements: jQuery, jExcel and jSuites v3
Here's a Working Example at CodePen

<kendo:pager pageSizes="pageSizes">

I'm trying to set pageSize in kendo:grid.
I've searched and I know it can be set via javascript using
pageable:{
pageSizes: [10, 20, 35, 50, 75, 100]
},
but the kendo:grid which I have does not use JavaScript. It uses Kendo-tag libraries in jsp.
This is my code structure:
<kendo:grid name="NameOfGrid" groupable="false" sortable="true">
<kendo:grid-pageable pageSizes="true" refresh="false" > </kendo:grid-pageable>
<kendo:grid-columns>
<kendo:grid-column title=" " field=" " width="60" sortable="true" />
There are new more <kendo:grid-colum>
</kendo:grid-columns>
<kendo:dataSource data="${"dataSource"}" pageSizes="[10,20,30,40]"> </kendo:dataSource>
</kendo:grid>
So, i'm using this way to set kendo:grid and everything work's perfect, but here i want to set own pageSize, by default when pageSize is kept true it has dropdown [5,10,20 and All ] but i want to change it and keep as [10, 20, 35, 50, 75, 100].
..
so can anyone help or show an example on how to set using . There are few documentation using it but i couldnot find a proper example.http://docs.telerik.com/kendo-ui/api/jsp/pager
Thank you so much for your time.
You can pass an Object array as predefined values to the pageSizes option, e.g.:
<%
Object pageSizes[] = {10, 50, 100, 250};
%>
...
<kendo:grid name="grid" groupable="true" sortable="true" style="height:550px;">
<kendo:grid-pageable refresh="true" pageSizes='<%= pageSizes %>' ...>

keybind to scroll down suggestions not working

I've set up typeahead to return search results. the results are returning correctly, however the expected functionality of being able to press the up and down buttons to cycle through the search results, to autocomplete the text box is not working. I cant figure out why.
var items = [{"Name":"TestAccount", "AccountID":"TestID"},{"Name":"TestAccount2", "AccountID":"TestID2"}]
var templ = Hogan.compile('<div class="search-result">{{Name}}</div>');
var myTA = $('.js-header-search-box').typeahead({
hint: true,
highlight: true,
minLength: 1
}, {
name: "Accounts",
valueKey: "AccountID",
engine: Hogan,
templates: {
empty: [
'<div class="empty-message">',
'unable to find any items that match the current query',
'</div>'
].join('\n'),
suggestion: function (data) { return templ.render(data); }
},
source: function (query, process) { process(items);
}
});
myTA.on('typeahead:selected', function (obj, datum) {
var id = datum['AccountID'];
document.location.href = area + '/Account/Edit' + id + '/';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="http://twitter.github.io/hogan.js/builds/3.0.1/hogan-3.0.1.js"></script>
<script src="https://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>
<input autocomplete="off" class="js-header-search-box header-search-box" placeholder="Account name or postcode" type="text" >
You need to use displayKey for that. Something like below
displayKey: function(accnt){
return accnt.Name;
}
displayKey – For a given suggestion object, determines the string representation of it. This will be used when setting the value of the input control after a suggestion is selected. Can be either a key string or a function that transforms a suggestion object into a string. Defaults to value.
Here is the reference
Here is a DEMO

displaying an individual integer in webix

I want to display a single number (that would change, that's why I'm not hard coding it) from am object. This, however, doesn't display anything.
var game_data = {
amount: 1,
yes_left: 3,
nos_left: 1
};
var game_panel = {
view: "form", id:"game_panel",
rows:[
{cols:[
{
template:'<span class="main_title">Money: $#amount#.00 </span>',
data:{amount:game_data.amount},align:"center"
},
}
]
};
I've also tried returning it as a variable:
template: function(game_data) {return '<span class="main_title">Money: ' + game_data.amount + '.00 </span>'}
Any ideas how to get that to display?
The code that you are using is correct. You can check the the next working snippet http://webix.com/snippet/82566e82
If you plan to update this number dynamically, it will be better to use a bit different syntax
id:"t1",
template:'<span class="main_title">Money: $#amount#.00 </span>',
data: game_data, align:"center"
and for number updating, be sure to call template.refresh, as template doesn't track data changes automatically.
game_data.amount += 2;
$$("t1").refresh();
http://webix.com/snippet/e3b0450d

Categories

Resources