JavaScript forEach loop overlapping divs - javascript

I have a code that converts JSON from database to a chart. But more than one JSON can come from the database in the form of an array.
I want it to convert all of them to charts with forEach, but it doesn't work. I think the divs are overlapping.
It always displays the latest data in chart form. What could be the problem? and how can it be solved?
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>
<div class="container">
<span style="margin-right: 5px;">Years: </span>
<span title="{{year.year}}"><input type="radio" id="id{{year.year}}" name="year" value="{{year.year}}" checked="checked"></span>
<label for="id{{year.year}}"></label>
<span title="{{year.year}}"><input type="radio" id="id{{year.year}}" name="year" value="{{year.year}}"></span>
<label for="id{{year.year}}"></label>
<span style="margin-left: 100px; margin-right: 5px;">Categories: </span>
<span title="{{category.name}}"><input type="radio" id="id{{category.name}}" name="category" value="{{category.name}}" checked="checked"></span>
<label for="id{{category.name}}"></label>
<span title="{{category.name}}"><input type="radio" id="id{{category.name}}" name="category" value="{{category.name}}"></span>
<label for="id{{category.name}}"></label>
<div class="chart-commands">
<select class="btn btn-primary command-btn">
<option value="EN">EN</option>
<option value="AZ">AZ</option>
</select>
</div>
</div>
<!-- Codes of charts -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
.highcharts-figure,
.highcharts-data-table table {
min-width: 310px;
max-width: 800px;
margin: 1em auto;
}
#container {
height: 400px;
}
.highcharts-data-table table {
font-family: Verdana, sans-serif;
border-collapse: collapse;
border: 1px solid #ebebeb;
margin: 10px auto;
text-align: center;
width: 100%;
max-width: 500px;
}
.highcharts-data-table caption {
padding: 1em 0;
font-size: 1.2em;
color: #555;
}
.highcharts-data-table th {
font-weight: 600;
padding: 0.5em;
}
.highcharts-data-table td,
.highcharts-data-table th,
.highcharts-data-table caption {
padding: 0.5em;
}
.highcharts-data-table thead tr,
.highcharts-data-table tr:nth-child(even) {
background: #f8f8f8;
}
.highcharts-data-table tr:hover {
background: #f1f7ff;
}
</style>
</head>
<body>
<div class="container">
<div id="container" style="width:100%; height:400px;"></div>
<script type="text/javascript">
const jsonTables = ['[{"":"1","name":"data en","a":"5"}]', '[{"":"1","name":"data en","a":"56"},{"":"2","name":"data","a":"45"},{"":"3","name":"data","a":"74"}]', '[{"":"1","name":"data ru","a":"46"},{"":"2","name":"data","a":"72"},{"":"3","name":"data","a":"33"}]']
console.log(jsonTables)
jsonTables.forEach((table) => {
console.log(table);
var jsonChart = JSON.parse(table)
// JSON.parse(JSON.parse('{{ chart_json_string | escapejs }}'))
let secColumn = []
for(let i=0; i<jsonChart.length; i++){
let key=Object.keys(jsonChart[i])[1]
secColumn.push(jsonChart[i][key])
}
let all = []
for(let i=0;i<jsonChart.length;i++){
for(let j=2;j<Object.keys(jsonChart[i]).length;j++){
all.push(Object.keys(jsonChart[i])[j])
}
}
let keys = [...new Set(all)];
let column = []
for (let key of keys) {
let x = jsonChart.map(e => {
if(e[key]){
return Number(e[key].replace("%",""))
}
})
column.push({ name: key, data: x })
}
document.addEventListener('DOMContentLoaded', function () {
const chart = Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Name'
},
xAxis: {
categories: secColumn
},
yAxis: {
title: {
text: 'Values'
}
},
series: column
});
});
});
</script>
</div>
</body>

You have configured the series as series: column. You need to separate your data and put it into data arrays.
You can use a basic column, stacked column, or column comparison but all of them use a series array, e.g.
series: [{
name: 'BPL',
data: [3, 5, 1, 13]
}, {
name: 'FA Cup',
data: [14, 8, 8, 12]
}, {
name: 'CL',
data: [0, 2, 6, 3]
}]
See demo pages on highcharts.com:
https://www.highcharts.com/demo/column-basic
https://www.highcharts.com/demo/column-stacked
https://www.highcharts.com/demo/column-comparison
The demo pages allow you to open the code in jsfiddle or codepen.

Related

Local Storage with multiple contentEditable

I have currently figured out a way to store value of 6am plan in a content editable box in my local storage key
item 2
How do I make this happen for all the other hours like 1
work plan for every hour of the day 6 am - 11pm
storing input in one key
using this code snippet below
javascript -
var content = document.getElementById('content'),
address = document.getElementById('address'),
saveButton = document.getElementById('save'),
loadButton = document.getElementById('load'),
clearButton = document.getElementById('clear'),
resetButton = document.getElementById('reset');
var localStore = {
saveLocalStorage: function() {
localStorage.setItem('item', content.innerHTML);
},
loadLocalStorage: function() {
var contentStored = localStorage.getItem('item');
if ( contentStored ) {
content.innerHTML = contentStored;
}
},
clearLocalStorage: function() {
localStorage.removeItem('item');
}
};
saveButton.addEventListener('click', function() {
localStore.saveLocalStorage();
}, false);
<r class="notion-table-row">
<td
style="color: inherit; fill: inherit; border: 1px solid gb(233, 233, 231); position: relative; vertical-align: top; min-width: 122px; max-width: 122px; min-height: 32px;">
<div class="notion-table-cell">
<div class="notion-table-cell-text"
spellcheck="true" placeholder=" "
data-content-editable-leaf="true"
style="max-width: 100%; width: 100%; white-space: pre-wrap; word-break: break-word; caret-colour: gb(55, 53, 47); padding: 7px 9px; background-colour: transparent; font-size: 14px; line-height: 20px;"
content editable="false">11 PM</div>
</div>
</td>
<td
style="color: inherit; fill: inherit; border: 1px solid gb(233, 233, 231); position: relative; vertical-align: top; min-width: 200px; max-width: 200px; min-height: 32px;">
<div class="notion-table-cell">
<div class="notion-table-cell-text"
spellcheck="true" placeholder=" "
data-content-editable-leaf="true"
style="max-width: 100%; width: 100%; white-space: pre-wrap; word-break: break-word; caret-colour: gb (55, 53, 47); padding: 7px 9px; background - colour: transparent; font-size: 14px; line-height: 20px;"
<section id="11pm_input" content editable="true"></div>
Store all of the data in an array. Keep in mind, localStorage stores only strings so anything not a string (ex. array, object, number, etc.), must be converted into a string when saved to localStorage:
localStorage.setItem("String", JSON.stringify([...Array]))
and when it is retrieved from localStorge it needs to be parsed into it's original type:
const data = JSON.parse(localStorage.getItem("String"));
In the example below, the data is gathered from all .cell which comprise of the following HTML elements from the table head and body (in ex. 4 x time, 6 x data):
<time class='cell' datetime="23:00">11 PM</time>
<data class='cell' value="0ne Zer0">Zer0 0ne</data>
time.datetime = "23:00";
time.textContent = "11 PM";
data.value = "0ne Zer0";
data.textContent = "Zer0 0ne";
lStorage = [
["23:00", "11 PM"],
["0ne Zer0", "Zer0 0ne"],
["00:00", "12 AM"],
...[N, N]
];
The event handler manageData(event) delegated all click events triggered on the table head, body, and foot.
Variables:
key is whatever the user typed in .input, the value will be assigned to data being saved to localStorage.
data is declared for data coming from and to localStorage.
cells is an array of all time.cell and data.cell tags within the table head and body.
node is determined by event.target property which always refers to the tag the user actually clicked. This reference will be delegated to react according to the .matches() method and a series of flow control statements (if, if else, and else).
The process for loading data from localStorage involves loadData(key) and iteration of the array of arrays saved in localStorage and the array of .cells:
if (node.matches('.load')) {...
...
data = loadData(key);
cells.forEach((n, i) => {
n.textContent = data[i][1];
if (n.matches('time')) {
n.datetime = data[i][0];
} else {
n.value = data[i][0];
}
});
The rest of the code is of simular fashion -- here's a brief description of what it can do:
Load data from key in localStorage and popualte a <table> with it.
Save data from a <table> to a key in localStorage.
Reset data the user typed in the fields (if given a selector, it can reset it as well).
Clear data by key and all data in <table> (including static data).
All .cells are editable (including headers). Double click any .cell within the table head or body to toggle it in/out of edit mode.
Due to SO security policy, WebStorage API will not function, go to: Plunker
The link doesn't work for me when clicked but
I managed to use the url by copy & paste
to the address bar:
https://run.plnkr.co/preview/ckz3pfkfe0007386nlancnzqk/
If the links above don't work, you can copy & paste the code in the Snippet with a text editor and save the file with a *.html extension.
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<style>
:root {
font: 1ch/1.5 'Segoe UI';
}
body {
font-size: 2ch;
}
table {
table-layout: fixed;
width: 70vw;
margin: 20px auto;
}
th {
width: 50%;
font-size: 2.25rem;
}
td {
vertical-align: center;
}
.box {
display: flex;
flex-flow: column nowrap;
justify-content: center;
align-items: center;
min-height: 32px;
padding: 8px 8px 5px;
}
.cell {
display: block;
max-width: 100%;
width: 100%;
min-height: 25px;
white-space: pre-wrap;
word-break: break-word;
font-size: 2rem;
border: 2px solid #000;
background: transparent;
text-align: center;
}
.head {
width: 97.5%;
border-color: transparent;
}
.edit {
border-color: blue;
}
button {
display: block;
font: inherit;
font-size: 2rem;
background: transparent;
border-radius: 6px;
cursor: pointer;
}
button:hover {
border-color: blue;
color: blue;
background: #ddd;
}
.ctrl {
position: relative;
flex-flow: row nowrap;
justify-content: space-between;
min-width: 92%;
height: 30px;
margin-top: 40px;
}
.input {
position: absolute;
top: -40px;
left: -0.5vw;
width: 99%;
height: 25px;
}
.noKey {
color: tomato;
font-weight: 900;
border-color: tomato;
}
.noKey::before {
content: 'Enter the key to data';
}
.done {
color: blue;
border-color: blue;
}
.done::before {
content: 'Data is saved under key: "';
}
.done::after {
content: '"';
}
</style>
</head>
<body>
<main>
<section>
<table>
<thead>
<tr>
<th>
<data class="cell head" value="Hour">Hour</data>
</th>
<th>
<data class="cell head" value="Employee">Employee</data>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<fieldset class="box">
<time class="cell">8 PM</time>
</fieldset>
</td>
<td>
<fieldset class="box">
<data class="cell edit" contenteditable></data>
</fieldset>
</td>
</tr>
<tr>
<td>
<fieldset class="box">
<time class="cell">9 PM</time>
</fieldset>
</td>
<td>
<fieldset class="box">
<data class="cell edit" contenteditable></data>
</fieldset>
</td>
</tr>
<tr>
<td>
<fieldset class="box">
<time class="cell">10 PM</time>
</fieldset>
</td>
<td>
<fieldset class="box">
<data class="cell edit" contenteditable></data>
</fieldset>
</td>
</tr>
<tr>
<td>
<fieldset class="box">
<time class="cell">11 PM</time>
</fieldset>
</td>
<td>
<fieldset class="box">
<data class="cell edit" contenteditable></data>
</fieldset>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2">
<fieldset class="ctrl box">
<data class="cell input edit" contenteditable></data>
<button class="load" title="Load data">
Load</button>
<button class="save" title="Save data">
Save</button>
<button class="reset" title="Reset fields">
Reset</button>
<button class="clear" title="Clear saved data and Reset fields">
Clear</button>
</fieldset>
</td>
</tr>
</tfoot>
</table>
</section>
</main>
<script>
const tab = document.querySelector('table');
const hdr = tab.tHead;
const mid = tab.tBodies[0];
const ftr = tab.tFoot;
const cls = ['noKey', 'done'];
const inp = document.querySelector('.input');
const formatTime = time => {
const T = time.split(' ');
return T[1] === 'PM' ? `${+T[0]+12}:00` : `${T[0]}:00`;
};
const lastFirst = name => name.split(' ').reverse().join(', ');
const loadData = key => JSON.parse(localStorage.getItem(key));
const saveData = (key, data) => localStorage.setItem(key, JSON.stringify(data));
const resetData = selector => {
let nodes = selector === undefined ? '.edit' : selector;
[...document.querySelectorAll(nodes)].forEach(n => {
n.textContent = '';
if (n.matches('time')) {
n.datetime = '';
} else {
n.value = '';
}
});
inp.classList.remove(...cls);
};
const clearData = key => {
resetData('.cell');
inp.classList.remove(...cls);
localStorage.removeItem(key);
};
const manageData = e => {
let key = inp.textContent;
let data;
const cells = [...document.querySelectorAll('.cell')];
const node = e.target;
if (node.matches('.load')) {
if (key.length < 1) {
inp.classList.add('noKey');
} else {
data = loadData(key);
cells.forEach((n, i) => {
n.textContent = data[i][1];
if (n.matches('time')) {
n.datetime = data[i][0];
} else {
n.value = data[i][0];
}
});
}
} else if (node.matches('.save')) {
if (key.length < 1) {
inp.classList.add('noKey');
} else {
data = cells.flatMap(n => {
if (n.matches('time')) {
n.datetime = formatTime(n.textContent);
return [
[n.datetime, n.textContent]
];
} else {
n.value = lastFirst(n.textContent);
return [
[n.value, n.textContent]
];
}
});
inp.classList.add('done');
saveData(key, data);
}
} else if (node.matches('.reset')) {
resetData();
} else if (node.matches('.clear')) {
if (key.length < 1) {
inp.classList.add('noKey');
} else {
clearData(key);
}
} else if (node.matches('.input')) {
node.textContent = '';
node.classList.remove(...cls);
} else {
return;
}
};
ftr.onclick = manageData;
const toggleEdit = e => {
const node = e.target;
if (node.matches('.cell')) {
node.classList.toggle('edit');
node.toggleAttribute('contenteditable');
}
};
hdr.ondblclick = toggleEdit;
mid.ondblclick = toggleEdit;
</script>
</body>
</html>

updating a div tag that pulls data from another site, I want that div to auto-refresh without having to reload the page

I want to update getPrice($url) function every 1sec without manual
page refresh
<?php
ini_set('display_errors', '1');
This function getPrice($url) currently refreshes only when i refresh page manually.
function getPrice($url)
{
$decode = file_get_contents($url);
return json_decode($decode, true);
}
$btcUSD = getPrice('https://btc-e.com/api/2/btc_usd/ticker');
$btcPrice = $btcUSD ["ticker"]["last"];
$btcDisplay = round($btcPrice, 2);
?>
HTML code begins here.
<html>
<title>Coin-Co. | Welcome!</title>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<style>
h1
{
font-family: "Calibri", Arial, sans-serif;
font-size: 80px;
}
This is the div for function getPrice($url)
#container
{
font-family: "Calibri", Arial, sans-serif;
font-size: 60px;
border: 3.8px solid #666666;
border-radius: 5px;
height: 75px;
width: 425px;
}
#containerConvert
{
font-family: "Calibri", Arial, sans-serif;
font-size: 38px;
border: 2.9px solid #666666;
border-radius: 5px;
height: 63px;
width: 497px;
}
#bi , #ci
{
font-family: "Calibri", Arial, sans-serif;
font-size: 21px;
border: 2.9px solid #999999;
border-radius: 1.75px;
height: 48.7px;
width: 148px;
}
</style>
</head>
<body>
<script>
var chart;
function requestData() {
$.ajax({
url: 'live_btce.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is
// longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'containerChart',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Live feed BTCe 5second-Chart'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'USD',
margin: 80
}
},
series: [{
name: 'BTC->USD',
data: []
}]
});
});
</script>
<center>
<h1><em>BTC|USD</em></h1>
<div id="container"><?php echo $btcDisplay; ?></div></br>
<script>
function btcConvert(input)
{if (isNaN(input.value))
{
input.value = 0;
}
var price = "<?php echo $btcDisplay; ?>";
var output = input.value * price;
var co = document.getElementById('ci');
ci.value = output.toFixed(2);
}
function usdConvert(input)
{if (isNaN(input.value))
{
input.value = 0;
}
var price2 = "<?php echo $btcDisplay; ?>";
var output2 = input.value / price2;
var co2 = document.getElementById('bi');
bi.value = output2.toFixed(8);
}
</script>
<div id="containerConvert">
<input type="text" name="bi" id="bi" onchange="btcConvert(this);" onkeyup="btcConvert(this);" /> BTC =
<input type="text" name="ci" id="ci" onchange="usdConvert(this);" onkeyup="usdConvert(this);" /> USD
</div>
<div id="containerChart" style="width:100%; height:400px;"></div>
</body>
</html>
At the end of your php code you are missing
echo $btcDisplay;
and before adding point in javascript parse it as float
// add the point
point = parseFloat(point);
chart.series[0].addPoint(point, true, shift);

Fade in Function Won't work with Chart in Flot

I have the following code that make a simple line chart of price during the day
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Flot Line Graph</title>
<style type="text/css">
body { font-family: Verdana, Arial, sans-serif; font-size: 12px; }
h4 { width: 450px; margin-left:200px; font-size: 12px; text-align: center; }
#placeholder { width: 450px; height: 200px; position: relative;}
.legend table, .legend > div { height: 50px !important; opacity: 1 !important; right: -55px; top: 10px; width: 80px !important; }
.legend table { border: 3px solid #555; padding: 5px; font-weight:800; }
.col-md-1{width:50px !important;;
padding:0px !important;;}
.col-md-4{padding: 0px !important;;}
form{font-weight: 800;}
</style>
<!--[if lte IE 8]><script type="text/javascript" language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/flot/0.8.2/excanvas.min.js"></script><![endif]-->
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/flot/0.8.2/jquery.flot.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/flot/0.8.2/jquery.flot.symbol.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/flot/0.8.2/jquery.flot.time.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
<div class="row">
<div class = "col-md-1" style="width:100px; margin-left:100px; margin-top:40px">
<form>
<input id="price_cat" type="radio" name="price_val" value="0" checked> LMP<br>
<input id="price_cat" type="radio" name="price_val" value="1"> MLC<br>
<input id="price_cat" type="radio" name="price_val" value="2">MCC
</form>
</div>
<div class="col-md-4">
<h4 id ="title"></h4>
<div id="placeholder" style = "width:850px; height:450px"></div>
<h4>Hour</h4>
</div>
</div>
</body>
<script type="text/javascript">
//Rome, Italy
var mkt_data = $.getJSON('https://bc2.demo.socrata.com/resource/9kzc-t3jm.json', function(response) {
console.log(response);
});
$.when(mkt_data).then(function(data) {
var price_data = data
var collection = []
var lmp_c =[]
var mcc_c = []
var mlc_c = []
var series = []
data.forEach(function(a) {
var lmp_s = []
var mcc_s = []
var mlc_s = []
lmp_s.push(Number(a.hour.replace("HE","")),Number(a.lmp));
lmp_c.push(lmp_s);
mcc_s.push(Number(a.hour.replace("HE","")), Number(a.mcc));
mcc_c.push(mcc_s)
mlc_s.push(Number(a.hour.replace("HE","")), Number(a.mlc));
mlc_c.push(mlc_s)
})
series.push({label:"LMP", data: lmp_c},{label:"MLC", data: mlc_c},{label:"MCC", data: mcc_c})
console.log(series[0].label);
$("#title").html("Average LMP per hour of the Day Jan - June 2016")
$.plot($("#placeholder"), [series[0]], {xaxis: {
min:0,
max:24,
tickSize: [1]
},
legend: {
labelBoxBorderColor: "none",
position: "right"
},
series: {lines: { show: true },
points: {
radius: 3,
show: true,
fill: true
}
}
});
$("input:radio[name=price_val]").change(function(){
var price_series = Number($('input:radio[name=price_val]:checked').val());
console.log(price_series, typeof price_series);
$("#title").html("Average "+series[price_series].label+" per hour of the Day Jan - June 2016")
$.plot($("#placeholder").fadeIn(500), [series[price_series]], {xaxis: {
min:0,
max:24,
tickSize: [1]
},
legend: {
labelBoxBorderColor: "none",
position: "right"
},
series: {lines: { show: true },
points: {
radius: 3,
show: true,
fill: true
}
}
});
});
});
the chart work and so does the change listener but I can't get the fade in to work properly. I would usually attached it to the element selector but the flot libraries $.plot() function is making it unclear to me where I should put the call to fadeIn(). I just want to achieve a smoother transition when changing datasets. The fade in call is at line 114.

How to capture the DataValueField of the autocomplete componet of kendoUI?

Hello I am working with Kendo UI, specifically with kendoAutoComplete component. I can get the value of autocomplete field, but I need the id value associated with it.
$("#autocomplete").kendoAutoComplete({
minLength: 3,
dataTextField: "Name", //JSON property name to use
dataValueField: "Id",
dataSource: respuestaSolicitud
});
I captured of this way
var x=$('#autocomplete').data("kendoAutoComplete");
Variable x return [object]
document.getElementById('autocomplete').value
return value of dataTextField: "Name"
But I need integer value dataValueField: "Id"
$(document).ready(function () {
var data = [{Name:"aaaa",Id:1111},{Name:"bbbb",Id:2222}
];
//create AutoComplete UI component
$("#countries").kendoAutoComplete({
dataSource: data,
change: function(e){
alert(this.dataItem().Id)
},
dataTextField: "Name", //JSON property name to use
dataValueField: "Id",
filter: "startswith",
placeholder: "Select country...",
separator: ", "
});
});
function _getValue(){
alert($("#countries").data("kendoAutoComplete").value())
}
.info {
display: block;
line-height: 22px;
padding: 0 5px 5px 0;
color: #36558e;
}
#shipping {
width: 482px;
height: 152px;
padding: 110px 0 0 30px;
background: url('../content/web/autocomplete/shipping.png') transparent no-repeat 0 0;
margin: 100px auto;
}
.k-autocomplete
{
width: 250px;
vertical-align: middle;
}
.hint {
line-height: 22px;
color: #aaa;
font-style: italic;
font-size: .9em;
color: #7496d4;
}
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.429/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.429/styles/kendo.material.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.429/styles/kendo.dataviz.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.429/styles/kendo.dataviz.material.min.css" />
<script src="http://cdn.kendostatic.com/2015.1.429/js/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2015.1.429/js/kendo.all.min.js"></script>
<div id="example">
<div id="shipping">
<button onclick="_getValue()">press me</button>
<label for="countries" class="info">Choose shipping countries:</label>
<input id="countries" />
<div class="hint">Start typing the name of an European country</div>
</div>
you can use underscore to find the result
var selected = $("#countries").data("kendoAutoComplete").value();
var dataItem = _.find($("#$("#countries").data("kendoAutoComplete").dataSource.data(),function(element){
return element.Name=== selected;
})
alert (dataItem.Id)
another approach would be to use a change event and onthat event you get the full element with this.dataItem() so you get the Id with
this.dataItem().Id

How to add spliced values again to a list without refreshing the page

I am a newbie to angular JS and having problem in adding the spliced value back to the list.
How cam i do so or can i use any other Angular JS function in place of splice to do the need full.
Below is the code i have do.
{
<!DOCTYPE html>
<html>
<head>
<title>Drag Drop + Remove Element</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootswatch/2.3.1/spruce/bootstrap.min.css">
<style>
[ng-drag] {
width: 100px;
height: 100px;
background: red;
color: white;
text-align: center;
padding-top: 40px;
display: block;
}
[ng-drop] {
background: silver;
text-align: center;
display: block;
position: relative;
padding: 20px;
width: 140px;
height: 140px;
float: left;
}
.draglist {
display: inline-block;
margin: 0 auto;
}
[ng-drag].dragging {
opacity: 0.5;
}
[ng-drag].drag-over {
border: solid 1px red;
}
[ng-drop].drag-enter {
border: solid 5px red;
}
</style>
</head>
<body ng-app="ExampleApp">
<div class="row text-center">
<h1>Drag Drop + Remove Element</h1>
</div>
<div class="row text-center" ng-controller="MainCtrl">
<ul class="draglist">
<li ng-repeat="obj in draggableObjects | limitTo:quantity" ng-drop="true" ng-drop-success="onDropComplete($index, $data,$event)" >
<button type="button" class="close" ng-click="removeElement($index,draggableObjects.length)"><span aria-hidden="true" ng-mouseover>×</span></button>
<div ng-drag="true" ng-drag-data="obj" ng-class="obj.name">
{{obj.name}}
</div>
</li>
</ul>
</div>
<!--<script src="http://code.angularjs.org/1.3.15/angular.min.js"></script>-->
<script src="Angular.js"></script>
<script src="ngDraggable.js"></script>
<script>
angular.module('ExampleApp', ['ngDraggable']).
controller('MainCtrl', function ($scope, $window) {
$scope.draggableObjects = [
{name: 'one'},
{name: 'two'},
{name: 'three'},
{name: 'four'},
{name: 'five'},
{name: 'six'},
{name: 'seven'},
{name: 'eight'},
{name: 'nine'},
{name: 'ten'}
];
$scope.quantity = 3;
$scope.showDelete = false;
$scope.removeElement = function(index, objLength){
console.log("objLength::"+objLength);
$scope.showDelete = true;
if(objLength < 4){
console.log("In if");
// $window.location.reload();
// $scope.draggableObjects;
console.log($scope.draggableObjects);
$scope.draggableObjects = $scope.draggableObjects.concat($scope.draggableObjects);
// angular.forEach($scope.draggableObjects, function(objects) {
// $scope.draggableObjects.push(objects);
//// console.log($scope.draggableObjects);
// });
}
else{
$scope.draggableObjects.splice(index,1);
}
};
$scope.onDropComplete = function (index, obj, evt) {
var otherObj = $scope.draggableObjects[index];
var otherIndex = $scope.draggableObjects.indexOf(obj);
$scope.draggableObjects[index] = obj;
$scope.draggableObjects[otherIndex] = otherObj;
};
});
</script>
</body>
</html>
}
Now what i want to do is once the value get spliced from the $scope.draggableObjects i want to add the spliced data again at the end of the code so that a cycle is continued of all the values in scope.
Any help will be welcomed.
Thanks in advance.
just javascript
$scope.draggableObjects.push(obj) // obj prev removed

Categories

Resources