Select2, need to group results into one for display - grouping

I use "multiple select boxes" (select2 examples) and I want to group showing results:
like (only if selected more then X options):
Whithout this the field with the results will be too large. Also, I don't want to make a scroll in the field results.
Is there any ready solution to do this?

I created the solution:
$(document).ready(function() {
$(".test").select2();
});
function select_grouping(obj) {
var min_grouping_count = 3;
var title = ' elements selected';
var count = 0;
if (obj.children('li').length > min_grouping_count) {
if (obj.children('li').length > min_grouping_count) {
count = obj.children('li').length - 1;
obj.children('li').each(function(index, el) {
if (index > 0 && index < count) {
$(this).remove();
}
});
}
obj.children('li:eq(0)').html(count + title);
}
}
$(".test").on("select2:select", function(obj) {
var obj = $('#filtr_test').find('.select2-selection__rendered');
select_grouping(obj);
});
$(".test").on("select2:unselect", function(obj) {
var obj = $('#filtr_test').find('.select2-selection__rendered');
select_grouping(obj);
});
.test {
width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
<div id="filtr_test">
<select class="test" multiple="multiple">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
<option value="5">five</option>
<option value="6">six</option>
<option value="7">seven</option>
</select>
</div>

Related

How to render element depends on selected option?

i'm newbie in react js , and i want to have a form with select options
i want that when user click on each option , each option render different elements
class Resepy extends Component {
state = {
Resepy : 'default'
}
render() {
return = (
<div className="Resepy">
<form>
<select id="id_field1" name="field1" onChange={(e) => this.state.Resepy = "Burger"}>
<option value="default">Food type not selected</option>
<option value="burger" onClick={(e) => this.setState({ Resepy: 'Burger' })}>Burger</option>
<option value="pizza" onClick={(e) => this.setState({ Resepy: 'Pizza' })}>Pizza</option>
</select>
<div className="food">
{ this.state.Resepy === "burger" ? <div className="burger"></div> //can return any html
: <div className="default">default</div>
}
<div className="pizza"></div>
<div className="food-detail"></div>
</div>
<button type="submit">Add to tray</button>
</form>
</div>
);
}
}
export default Resepy;
General ternary operator used for more readable code.
Like this:
<form>//can be any element
{ codition == true ? <div>It is true</div> //can return any html
: <div>It is false</div>
}
</form>
Tested, working. Problem was with onClick method option cannot invoke that event.
class Resepy extends React.Component {
constructor(props){
super(props);
this.state = {
selected : 'default'
};
}
setSelected = (event) => {
let select = document.getElementById("id_field1");
this.setState({selected: select.value});
//document.getElementById("test").innerHTML = select.value;
}
render() {
return (
<div className="Resepy">
<h1>Something</h1>
<form>
<select id="id_field1" name="field1" onChange={this.setSelected}>
<option value="default">Food type not selected</option>
<option value="burger">Burger</option>
<option value="pizza">Pizza</option>
</select>
<div id="test"></div>
<div className="food">{
(this.state.selected === "default") ?
<div className="default">Default</div>
: (this.state.selected === "burger") ?
<div className="burger">Burger</div>
: <div className="pizza">Pizza</div>
}</div>
<button type="submit">Add to tray</button>
</form>
</div>
);
}
}
I have a hard time understanding you, but the most likely thing you could be trying to achieve with the following code from your original question:
<div className="burger" Resepy={this.state.Resepy === 'burger'}></div>
is:
<div className="food">
<div className={this.state.Resepy} />
</div>
Working example (but I am using Hooks instead of a class component):
const App = () => {
const [selected, setSelected] = React.useState('default')
const handleChange = (event) => {
setSelected(event.target.value)
}
return (
<div>
<select value={selected} onChange={handleChange}>
<option>default</option>
<option>burger</option>
<option>pizza</option>
</select>
<div className="food">
<div className={selected}>{selected}</div>
</div>
</div>
)
}
ReactDOM.render(<App />, document.getElementById('root'))
.default { color: gray; }
.burger { color: orange; }
.pizza { color: red; }
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<div id="root"></div>
Now i want to render html elements depends on values , i tried this but it shows just [Object Object]
setSelected = (event) => {
let select = document.getElementById("id_field1");
document.getElementById("food").innerHTML =
select.value == "default" ?
<div className="default">Default</div>
: select.value == "Burger" ?
<div className="burger">Burger</div>
: <div className="pizza">Pizza</div>
}

Spreadjs references from iframe

We use an iframe in the parent page, that is dynamically replaced with other pages.
Spread is loaded in the parent. Is there some type of plugin that will allow me to access the spread core that is loaded in the parent from the iframe pages without including spread(language="JavaScript" src="http://cdn.wijmo.com/spreadjs/gcspread.sheets.all.8.40.20151.0.min.js") in the multiple child (iframe) pages? Jquery is loaded fine.
Home page iframe with references
<iframe name="mainWindow" src="includes/View.asp frameborder="0" />
<link href="http://cdn.wijmo.com/spreadjs/gcspread.sheets.8.40.20151.0.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://cdn.wijmo.com/spreadjs/gcspread.sheets.all.8.40.20151.0.min.js"></script>
We just replace the iframe source at run time.
I use following code but spread is not initialized any suggestions ?
<script type="text/javascript">
var parentWindow = window.parent;// This refers to parent's window object
if (parentWindow && parentWindow.jQuery) { // Check to see if parentWindow and parentWindow.jQuery is truly
window.jQuery = parentWindow.jQuery;
window.$ = parentWindow.jQuery;
}
else {
var jScript = document.createElement('script');
jScript.setAttribute("type", "text/javascript");
jScript.setAttribute("src", "http://code.jquery.com/jquery-1.8.2.min.js"); // load jQuery here
}
if (parentWindow && parentWindow.wijmo && parentWindow.GcSpread) { // Check to see if parentWindow and parentWindow.wijmo and parentWindow.GcSpread is truly
window.GcSpread = parentWindow.GcSpread;
window.wijmo = parentWindow.wijmo;
}
else {
var jScript = document.createElement('script');
jScript.setAttribute("type", "text/javascript");
jScript.setAttribute("src", "http://cdn.wijmo.com/spreadjs/gcspread.sheets.all.8.40.20151.0.min.js"); // load gcspread here
}
$(document).ready(function () {
var test = window;
alert("JQuery loaded");
var spread = new GcSpread.Sheets.Spread(document.getElementById("ss"));
var spreadNS = GcSpread.Sheets;
spread.setSheetCount(3);
spread.bind(spreadNS.Events.ActiveSheetChanged, function (e, args) {
$("#activeSheetIndex").val(spread.getActiveSheetIndex());
});
$("#btnAddSheet").click(function () {
spread.addSheet(spread.getSheetCount());
});
$("#btnRemoveSheet").click(function () {
var activeIndex = spread.getActiveSheetIndex();
if (activeIndex >= 0) {
spread.removeSheet(activeIndex);
}
});
$("#btnClearSheets").click(function () {
spread.clearSheets();
});
$("#btnSetActiveSheetIndex").click(function () {
var index = $("#activeSheetIndex").val();
if (!isNaN(index)) {
index = parseInt(index);
if (0 <= index && index < spread.getSheetCount()) {
spread.setActiveSheetIndex(index);
}
}
});
});
</script>
<div class="sample-turtorial">
<div id="ss" style="width:100%; height:580px;border: 1px solid gray;"></div>
<div class="demo-options">
<div class="option-row">
<input type="button" style="width: 100px" value="Add Sheet" id="btnAddSheet" />
<input type="button" style="width: 100px" value="Remove Sheet" id="btnRemoveSheet" />
<input type="button" style="width: 100px" value="Clear Sheets" id="btnClearSheets" />
</div>
<div class="option-row">
<label>ActiveSheetIndex:</label>
<input type="text" id="activeSheetIndex" value="0" />
<input type="button" id="btnSetActiveSheetIndex" value="Set" />
</div>
</div>
</div>
I don't think what you're attempting work, how would the code execute without having a reference to the library (SpreadJS).
Can you please explain what your use case might be, may be we can help you find a different way of accomplishing what you need.

Google charts with Fusion Table Example error

Alright so I copy and pasted this example from google's chart tools documentation:
https://developers.google.com/fusiontables/docs/samples/gviz_datatable
I simply replaced their fusion table info with mine and am unable to get the table to appear.
This is what I have now with the fusion table set to public access:
<html>
<head>
<meta charset="UTF-8">
<title>Fusion Tables API Example: Google Chart Tools Data Table</title>
<link href="/apis/fusiontables/docs/samples/style/default.css"
rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', { packages: ['table'] });
function drawTable() {
var query = "SELECT 'fundraiser' as fundraiser, " +
"'price' as price, 'merchant' as merchant " +
'FROM 1QN6e86FybBULPekKvvXd_RF1jw01H7bZAJFjhUg';
var fundraiser = document.getElementById('fundraiser').value;
if (team) {
query += " WHERE 'fundraiser' = '" + fundraiser + "'";
}
var queryText = encodeURIComponent(query);
var gvizQuery = new google.visualization.Query(
'http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
gvizQuery.send(function(response) {
var table = new google.visualization.Table(
document.getElementById('visualization'));
table.draw(response.getDataTable(), {
showRowNumber: true
});
});
}
google.setOnLoadCallback(drawTable);
</script>
</head>
<body>
<div>
<label>Scoring Team:</label>
<select id="fundraiser" onchange="drawTable();">
<option value="">All</option>
<option value="default">default</option>
<option value="aaaatester">aaaatester</option>
</select>
</div>
<div id="visualization"></div>
</body>
</html>
I'm not sure what exactly was wrong with your query, but this works for me:
function drawTable () {
console.log('foo');
var query = 'SELECT fundraiser, price, merchant FROM 1QN6e86FybBULPekKvvXd_RF1jw01H7bZAJFjhUg';
var fundraiser = document.getElementById('fundraiser').value;
if (fundraiser) {
query += ' WHERE fundraiser = \'' + fundraiser + '\'';
}
var queryText = encodeURIComponent(query);
var gvizQuery = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
gvizQuery.send(function(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var table = new google.visualization.Table(document.getElementById('visualization'));
table.draw(response.getDataTable(), {
showRowNumber: true
});
});
}
function init () {
// draw the table
drawTable();
// setup the fundraiser dropdown to redraw the table when the user changes the value
var el = document.querySelector('#fundraiser');
if (document.addEventListener) {
el.addEventListener('change', drawTable);
}
else if (document.attachEvent) {
el.attachEvent('onchange', drawTable);
}
else {
el.onchange = drawTable;
}
}
google.load('visualization', '1', {packages: ['table'], callback: init});
With this as the HTML:
<div>
<label>Scoring Team:</label>
<select id="fundraiser">
<option value="">All</option>
<option value="default">default</option>
<option value="aaaatester">aaaatester</option>
</select>
</div>
<div id="visualization"></div>
I would suggest, however, that if you are going to have a filter like that, where your initial query is unfiltered, that you switch to using a CategoryFilter to filter your data in the browser instead of making a query to the server every time the user changes the filter. The only time making repeated queries to the server makes sense is when the total traffic to and from the server is likely to be substantially lower using multiple filtered queries than one single unfiltered query.

django csrf cookie no longer working

I don't understand why, but Django has ceased including the csrf cookie in responses. I have the middleware enabled, have tried using RequestContext and am using render. I have even tried using the csrf_protect and requires_csrf_token decorators.
I am working on a dev server right now, and I can print the context after I use RequestContext, and it seems to include a csrf_token.
But when I look at the actual headers using Chrome's inspect element, the csrf_token isn't there, also when I use the console and type in "document.cookie" that does not have the csrf token.
HELP!
Here's an example view
#requires_csrf_token
def index(request):
context = RequestContext(request, {'foo':'bar'})
print context
return render(request, 'index.html', context)
The CSRF token seems to be in the context:
{u'csrf_token': <django.utils.functional.__proxy__ object at 0x1025ab990>}, ...
But it fails to make its way through...
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Cookie:__utma=96992031.468590559.1369255550.1369255550.1369255550.1; __utmb=96992031.17.10.1369255550; __utmc=96992031; __utmz=96992031.1369255550.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)
Host:127.0.0.1:8000
Referer:http://127.0.0.1:8000/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31
UPDATE: Here is the template I'm using:
{% extends "base.html" %}
{% block hello %}
Basic Stock Event Charts
{% endblock %}
{% block content %}
<div id="leftsidebar">
<p>Use this tool to graph a time series data for a security. You can graph a security and
four other features such as volume, call option volume, or implied volatility. The tool will
zoom in on the date of interest to show the target audience the changes in the selected
vaiables preceeding the event. Because of large movement in variables before the announcement,
it may be helpful to use the minimum and maximum tools to zoom in on smaller movements ahead
of the event. </p>
<div class="ui-widget inline">
<label for="securities">1. Type in a ticker symbol</label>
<input id="securities">
</div>
<div class="inline"><input type="button" id="reload" value="Reset" class="hide" /></div>
<label for="datepicker">2. Pick your event date of interest.</label>
<input type="text" id="datepicker" disabled />
<label>3. Choose other series to graph.</label>
<p><strong>Primary Axis</strong></p>
Left Axis: <select id="series1" class="selectpicker span2" disabled><option value=""></option></select>
<div id="series1minmax" class="hide">
Min <input type="text" id="min1" class="input-mini" />
Max <input type="text" id="max1" class="input-mini" />
</div><input type="button" id="addaxes1" value="Graph" class="hide" />
<input type="button" id="removeaxes1" value="Remove" class="hide" /><br />
<br/>Right Axis: <select id="series2" class="selectpicker span2" disabled><option value=""></option>></select>
<div id="series2minmax" class="hide">
Min <input type="text" id="min2" class="input-mini" />
Max <input type="text" id="max2" class="input-mini" />
</div><input type="button" id="addaxes2" value="Graph" class="hide" />
<input type="button" id="removeaxes2" value="Remove" class="hide" /><br />
<input type="button" id="addextraaxis" value="Add Additional Axis" disabled/><br />
<div id="additional" class="hide">
<p><strong>Additional Axis</strong></p>
Left Axis: <select id="series3" class="selectpicker span2" disabled><option value=""></option></select>
<div id="series3minmax" class="hide">
Min <input type="text" id="min3" class="input-mini" />
Max <input type="text" id="max3" class="input-mini" />
</div><input type="button" id="addaxes3" value="Graph" class="hide" />
<input type="button" id="removeaxes3" value="Remove" class="hide" /><br />
<br/>Right Axis: <select id="series4" class="selectpicker span2" disabled><option value=""></option>></select>
<div id="series4minmax" class="hide">
Min <input type="text" id="min4" class="input-mini" />
Max <input type="text" id="max4" class="input-mini" />
</div><input type="button" id="addaxes4" value="Graph" class="hide" />
<input type="button" id="removeaxes4" value="Remove" class="hide" /><br />
</div>
</div>
<div id="rightsidebar">
<div id="container" class="hide"></div>
</div>
</div>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script src="http://code.highcharts.com/stock/highcharts-more.js"></script>
<script>
$(function() {
$("#removefromchart").click(function() {
var conceptName = $('#savedseries').find(":selected").remove();
});
$("#reload").click(function() {
location.reload();
})
$("#addextraaxis").click(function() {
$("#additional").removeClass("hide");
this.disabled = true
$("#addextraaxis").addClass("hide");
var chart = $("#container").highcharts();
chart.setSize(null, 650);
})
});
$(function() {
$("#series1").change(function() {
$("#addaxes1").removeClass("hide");
});
$("#series2").change(function() {
$("#addaxes2").removeClass("hide");
});
$("#series3").change(function() {
$("#addaxes3").removeClass("hide");
});
$("#series4").change(function() {
$("#addaxes4").removeClass("hide");
});
});
$(function() {
function setExtreme(isMin, axis, value) {
console.log("fired");
var chart = $('#container').highcharts();
if (isMin) {
console.log(value + " " + chart.yAxis[axis].getExtremes()["max"])
chart.yAxis[axis].setExtremes(value, chart.yAxis[axis].getExtremes()["max"]);
} else {
console.log(value + " " + chart.yAxis[axis].getExtremes()["min"])
chart.yAxis[axis].setExtremes(chart.yAxis[axis].getExtremes()["min"], value);
}
console.log(value);
}
function getAxisNumber(series) {
var indicies = {}
$.each(chart.yAxis, function(index, element) {
indicies[element.options.id] = index;
console.log(element.options.id);
});
return indicies[series]
}
$("#max1").change(function() {setExtreme(0, getAxisNumber("#series1"), this.value)});
$("#min1").change(function() {setExtreme(1, getAxisNumber("#series1"), this.value)});
$("#max2").change(function() {setExtreme(0, getAxisNumber("#series2"), this.value)});
$("#min2").change(function() {setExtreme(1, getAxisNumber("#series2"), this.value)});
$("#max3").change(function() {setExtreme(0, getAxisNumber("#series3"), this.value)});
$("#min3").change(function() {setExtreme(1, getAxisNumber("#series3"), this.value)});
$("#max4").change(function() {setExtreme(0, getAxisNumber("#series4"), this.value)});
$("#min4").change(function() {setExtreme(1, getAxisNumber("#series4"), this.value)});
});
$(function()
{
$("#removefromchart").click(function()
{
var conceptName = $('#savedseries').find(":selected").remove();
});
});
$(function() {
function addPlotLine(ts) {
var chart = $('#container').highcharts();
chart.xAxis[0].addPlotBand({
from: ts,
to: ((ts + 86400000) * 365),
color: 'rgba(68, 170, 213, 0.2)',
id: 'tsband'
});
chart.xAxis[0].addPlotLine({
value: ts,
color: 'rgb(255, 0, 0)',
width: 1,
id: 'tsline'
});
chart.xAxis[0].setExtremes(ts - (86400000 * 30), ts + 86400000)
}
function removeEventIfExists() {
var chart = $("#container").highcharts()
chart.xAxis[0].removePlotBand("tsband");
chart.xAxis[0].removePlotLine("tsline");
}
$("#datepicker").datepicker({
showButtonPanel: true, /*added by oussama*/
changeMonth: true, /*added by oussama*/
changeYear: true, /*added by oussama*/
dateFormat: 'yy-mm-dd',
onSelect: function (dateText, inst) {
utcDate = Date.UTC(dateText.split("-")[0], dateText.split("-")[1] - 1, dateText.split("-")[2]);
removeEventIfExists();
addPlotLine(utcDate);
$("#series1").removeAttr("disabled");
$("#series2").removeAttr("disabled");
$("#series3").removeAttr("disabled");
$("#series4").removeAttr("disabled");
$("#addextraaxis").removeAttr("disabled");
var ticker = $("#securities").val();
var date = $("#datepicker").val();
chart.setTitle({text: ticker + " around " + date});
}
});
});
$(function() {
function createChart() {
var chart = $('#container').highcharts();
var options = {chart: {
renderTo: 'container',
height: 450,
},
events: {
load: function(event) {
this.setExtremes();
}
},
rangeSelector: {
enabled: false,
},
exporting: {
enabled: false,
},
navigator: {
enabled: true,
series: { id: 'navigator' },
},
yAxis: [{
title: {
text: 'Price'
},
height: 150,
}],
},
chart = new Highcharts.StockChart(options);
return chart;
}
$("#securities").autocomplete({
source: "/api/get_securities/",
minLength: 1,
select: function(event, ui) {
var ticker = ui.item.label;
getSeries(ticker);
chart = createChart();
getTimeSeriesData(ticker + "|PX_LAST", 0);
$('#container').show();
$('#datepicker').removeAttr("disabled");
$('#reload').removeClass("hide");
chart.setTitle({text: ticker});
this.disabled = 'disabled';
},
});
});
$(function() {
function removeAxes(id) {
var chart = $('#container').highcharts();
chart.get(id).remove();
}
$("#removeaxes1").click(function() {
console.log("removeaxes1 clicked");
removeAxes("#series1");
$("#removeaxes1").addClass("hide");
$("#series1minmax").addClass("hide");
$("#series1minmax").removeClass("inline");
$("#series1").val("");
$("#min1").val("");
$("#max1").val("");
$("#series1").removeAttr("disabled");
});
$("#removeaxes2").click(function() {
console.log("removeaxes2 clicked");
removeAxes("#series2");
$("#removeaxes2").addClass("hide");
$("#series2minmax").addClass("hide");
$("#series2minmax").removeClass("inline");
$("#series2").val("");
$("#min2").val("");
$("#max2").val("");
$("#series2").removeAttr("disabled");
});
$("#removeaxes3").click(function() {
console.log("removeaxes3 clicked");
removeAxes("#series3");
$("#removeaxes3").addClass("hide");
$("#series3minmax").addClass("hide");
$("#series3minmax").removeClass("inline");
$("#series3").val("");
$("#min3").val("");
$("#max3").val("");
$("#series3").removeAttr("disabled");
});
$("#removeaxes4").click(function() {
console.log("removeaxes4 clicked");
removeAxes("#series4");
$("#removeaxes4").addClass("hide");
$("#series4minmax").addClass("hide");
$("#series4minmax").removeClass("inline");
$("#series4").val("");
$("#min4").val("");
$("#max4").val("");
$("#series4").removeAttr("disabled");
});
function addSeries(id, minMaxId, isOpposite, isAdditional) {
var chart = $('#container').highcharts();
indicies = {}
console.log('climlckedaddaxes');
var series = $(id).val()
var top = 210
if (isAdditional) top = 380
var options = {
title: {
text: series.split("|")[1]
},
top: top,
height: 150,
opposite: isOpposite,
id: id,
offset: -30
}
chart.addAxis(options)
$.each(chart.yAxis, function(index, element) {
indicies[element.options.id] = index;
console.log(element.options.id);
});
getTimeSeriesData(series, indicies[id]);
$(minMaxId).removeClass("hide")
$(minMaxId).addClass("inline")
}
$("#addaxes1").click(function() {
addSeries('#series1', "#series1minmax", false, false);
$("#addaxes1").addClass("hide")
$("#removeaxes1").removeClass("hide")
$("#series1").attr("disabled", "disabled")
});
$("#addaxes2").click(function() {
addSeries('#series2', "#series2minmax", true, false);
$("#addaxes2").addClass("hide")
$("#removeaxes2").removeClass("hide")
$("#series2").attr("disabled", "disabled")
});
$("#addaxes3").click(function() {
addSeries('#series3', "#series3minmax", false, true);
$("#addaxes3").addClass("hide")
$("#removeaxes3").removeClass("hide")
$("#series3").attr("disabled", "disabled")
});
$("#addaxes4").click(function() {
addSeries('#series4', "#series4minmax", true, true);
$("#addaxes4").addClass("hide")
$("#removeaxes4").removeClass("hide")
$("#series4").attr("disabled", "disabled")
});
})
$('#addtochart').click(function() {
var selectedValues = $('#seriesselector').val();
$.each(selectedValues, function(index, value) {
$('#savedseries').append($('<option>', {
value: value,
text: value,
selected: true,
}));
$('#seriesselector option[value="' + value +'"]').remove();
});
});
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function parseDate(inputdate, value) {
var date = inputdate;
var year = parseInt(date.split("-")[0]);
var month = parseInt(date.split("-")[1]) - 1;
var day = parseInt(date.split("-")[2]);
var outputdate = Date.UTC(year, month, day);
if (year == 2013 && month == 3) {
//console.log(inputdate, outputdate, value);
}
return outputdate;
};
function getTimeSeriesData(seriesName, axis) {
var csrftoken = getCookie('csrftoken');
console.log('csrftoken is :: ' + csrftoken);
$.ajax({ // create an AJAX call...
beforeSend: function(xhr, settings) {
var csrftoken = getCookie('csrftoken');
xhr.setRequestHeader("X-CSRFToken", csrftoken);
},
data: {'seriesName': seriesName }, // get the form data
type: 'POST',
url: '/api/get_time_series_data/',
success: function(response) { // on success..
console.log(response);
var series = {}
series['name'] = response[0]['series_name'];
series['data'] = []
$.each(response, function(index, value) {
series['data'][index] = [
parseDate(response[index]['date'], response[index]['value']),
parseFloat(response[index]['value'])
];
});
series['yAxis'] = axis
series['marker'] = {
enabled : true,
radius : 3
}
var chart = $('#container').highcharts();
chart.addSeries(series);
var nav = chart.get('navigator');
if (axis == 0) nav.setData(series['data']);
}
});
return false;
};
function getSeries(ticker) {
var csrftoken = getCookie('csrftoken');
$.ajax({ // create an AJAX call...
beforeSend: function(xhr, settings) {
var csrftoken = getCookie('csrftoken');
xhr.setRequestHeader("X-CSRFToken", csrftoken);
},
data: {'ticker': ticker }, // get the form data
type: 'POST',
url: '/api/get_series/',
success: function(response) { // on success..
$('#seriesselector').empty()
for (var i = 0; i < response.length; i++) {
if (response[i].value == 'PX_LAST') continue;
$('#series1').append($('<option>', {
value: ticker + "|" + response[i].value,
text: response[i].value
}));
$('#series2').append($('<option>', {
value: ticker + "|" + response[i].value,
text: response[i].value
}));
$('#series3').append($('<option>', {
value: ticker + "|" + response[i].value,
text: response[i].value
}));
$('#series4').append($('<option>', {
value: ticker + "|" + response[i].value,
text: response[i].value
}));
}
}
});
return false;
};
</script>
{% endblock %}
Turns out you need the
{% csrf_token %}
regardless of whether or not you are posting a html form. I was only doing AJAX requests, but Django won't include the token in the response header unless it sees it the template.

Gone fishing, because i like it

I have been trying to create Task manager with JavaScript and HTML. I'm quite new to programming, so hopefully someone will help me out with the following issue:
For some reason, the items of the array will not get into the table. Any helpful idea to solve this enigma? All help is appreciated!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
window.onload = init;
var descriptionS = new Array();
function init(){
var delBtn = document.getElementById("buttonDel");
delBtn.addEventListener('click', deleteRow, false);
var addTaskBtn = document.getElementById("addTask");
addTaskBtn.addEventListener('click', getTaskData, false);
var displayListBtn = document.getElementById("displayList");
displayListBtn.addEventListener('click', generateList, false);
var sortByNumBtn = document.getElementById("sortByNumber");
sortByNumBtn.addEventListener('click', sortListByNum, false);
}
function getTaskData(){
var myDescription = document.getElementById("descriptionField").value;
var myDate = document.getElementById("dateField").value;
var myPriority = document.getElementById("selRow0").value;
var description = new Object();
description.descriptionData = myDescription;
description.descriptionDate = myDate;
description.descriptionPriority = myPriority;
descriptionS.push(description);
}
function generateList(){
var myTaskList = document.getElementsByTagName("td");
myTaskList.innerHTML ="";
for(var p = 0; p < descriptionS.length; p++){
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
//Select cell
var cell0 = row.insertCell(0);
var selT = document.createElement("input");
selT.type = 'checkbox';
selT.name = 'chkBox';
selT.id = 'chkBox';
cell0.appendChild(selT);
// ID cell
var cell1 = document.createElement("td");
cell1 = row.insertCell(1);
var idFill = document.createTextNode(iteration);
cell1.appendChild(idFill);
cellSelect.appendChild(cell1);
//Description cell
var cell2 = document.createElement("td");
cell2 = row.insertCell(2);
var elF = document.createTextNode(descriptionS[p].descriptionData);
//elF.innerHTML = document.getElementById("descriptionField").value;
cell2.appendChild(elF);
// Priority cell
var cellPri = document.createElement("td");
cellPri = row.insertCell(3);
var pri = document.getElementbyId('selRow0').value;
pri.name = 'selRow' + iteration;
cellPri.appendChild(pri);
//Date
var cell4 = document.createElement("td");
cell4 = row.insertCell(4);
var elF1 = document.createTextNode(descriptionS[p].descriptionDate);
//elF.innerHTML = document.getElementById("descriptionField").value;
cell4.appendChild(elF1);
// Delete cell
var cell5 = document.createElement("td");
cell5 = row.insertCell(5);
var del1 = document.createElement('input');
del1.type = 'button';
del1.name = 'buttonDel';
del1.id = 'buttonDel';
del1.value = "Delete";
del1.onclick = function () {
var table = document.getElementById("tblSample");
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
};
cell5.appendChild(del1);
}
}
function sortListByNum(){
descriptionS.sort(sortFunctionByNumber);
generateList();
}
function sortFunctionByNumber(a, b){
return a.descriptionData-b.descriptionData;
}
function deleteRow(tableID) {
var table = document.getElementById("tblSample");
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
}
</script>
</head>
<body>
<form action="">
<p>
Description: <input type="text" id="descriptionField" />
Date: <input type="text" id="dateField" />
Priority: <select name="selRow0" id="selRow0" />
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="button" id="addTask" value="Add Task" />
<input type="button" id="displayList" value="Display Task" />
<input type="button" id="sortByNumber" value="Sort" />
</p>
<p>
<span id="spanOutput" style="border: 1px solid #000; padding: 3px;"> </span>
</p>
<table border="1" id="tblSample">
<tr>
<th>Select</th>
<th>ID</th>
<th>Description</th>
<th>Priority</th>
<th>Date</th>
<th>Delete</th>
</tr>
<tr>
<td><INPUT type="checkbox" name="chk"/></td>
<td>1</td>
<td>Example</td>
<td>
<select name="selRow1">
<option value="value1">1</option>
<option value="value2">2</option>
<option value="value3">3</option>
</select>
</td>
<td>06/06/2013</td>
<td>
<input type="button" value="Delete" id="buttonDel" />
</td>
</tr>
</table>
</form>
</body>
</html>
Use ExtJS GridPanel http://docs.sencha.com/ext-js/4-1/#!/example/grid/cell-editing.html
(Click to edit cell)