jquery change svg fill color twice - javascript

I'm trying to change the color of an SVG object with a jQuery, but after that i want to reset all fill attribute in class st24.
But after reset setAttribute doesn't work.
//Автокомплит
$(function() {
$( "#users" ).autocomplete({
source: function( request, response ) {
$.ajax({
cache: true,
url: "http://127.0.0.1/json.php",
dataType: "json",
success: function(data) {
response($.map(data, function(item){
return {
label: item.username,
placeId: item.LocationInfo.placeId,
}}));
}
});
},
minLength: 2,
select: function(event,ui) {
$('#users').val(ui.item.username);
$('#placeId').val(ui.item.placeId);
console.log(ui.item.placeId);
console.log(svgdom);
var svgElement = svgdom.getElementById(ui.item.placeId);
//Если id елемента есть в svg файле - меняем аттрибур fill, если нет генерируем алерт
if (svgElement) {
var st24 = svgdom.getElementsByClassName("st24");
$.each(st24, function( i, val) {
val.setAttribute("fill", "none");
});
svgElement.setAttribute("fill", "#008000");
} else {
generate('information');
}
}
});
});
});
If i try this:
$.each(st24, function( i, val) {
val.setAttribute("fill", "#008000");
});
work perfect - all elements have this attribute, but when i change setAttribute fill to none, and add this line: svgElement.setAttribute("fill", "#008000"); after this code, it doesn't work - why ?
Update:
This all my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="libs/jquery-2.1.1.min.js"></script>
<script src="libs/jquery-ui-1.10.4.js" type="text/javascript"></script>
<script src="libs/jquery.panzoom.js"></script>
<script src="libs/jquery.mousewheel.js"></script>
<script src="libs/noty/packaged/jquery.noty.packaged.min.js" type="text/javascript"></script>
<script src="libs/svg-pan-zoom.min.js"></script>
<link href="css/style.css" rel="stylesheet">
<link type="text/css" href="css/jquery-ui-1.10.4.custom.css" rel="stylesheet" />
</head>
<body>
<a id="link" href="admin.html">Admin</a>
<div class="ui-widget">
<label for="users">users: </label>
<input id="users" type="text" />
<input readonly="readonly" id="placeId" name="placeId" />
</div>
<embed src="svg/5.svg" width="900" height="900" id="imap"/>
<script>
//Всплывающие сообщения
function generate(type) {
var n = noty({
text : "Sorry place not found",
type : type,
dismissQueue: true,
layout : 'topCenter',
theme : 'defaultTheme',
timeout: 2000,
});
}
function generateInf() {
generate('information');
}
// Начинаем работу когда страница полностью загружена (включая графику)
$(window).load(function () {
// Получаем доступ к SVG DOM
var svgdom = document.getElementById('imap').getSVGDocument();
svgPanZoom('#imap', {
zoomEnabled: true,
controlIconsEnabled: true
});
function clearSvg() {
var st24 = svgdom.getElementsByClassName("st24");
$.each(st24, function(i, val) {
val.removeAttribute("fill");
});
}
function setColor(elem) {
elem.setAttribute("fill", "#008000");
}
//Автокомплит
$(function() {
$( "#users" ).autocomplete({
source: function( request, response ) {
$.ajax({
cache: true,
url: "http://127.0.0.1/json.php",
dataType: "json",
success: function(data) {
response($.map(data, function(item){
return {
label: item.username,
placeId: item.LocationInfo.placeId,
}}));
}
});
},
minLength: 2,
select: function(event,ui) {
$('#users').val(ui.item.username);
$('#placeId').val(ui.item.placeId);
console.log(ui.item.placeId);
console.log(svgdom);
var svgElement = svgdom.getElementById(ui.item.placeId);
//Если id елемента есть в svg файле - меняем аттрибур fill, если нет генерируем алерт
if (svgElement) {
clearSvg();
setColor(svgElement);
} else {
generate('information');
}
}
});
});
});
</script>
</body>
</html>

Setting fill to none doesn't delete the fill. It is saying "this element has no fill". So setting fill on the <svg> parent doesn't override that. The value on the child takes precendence.
If you want to remove the fill setting from the children use
val.removeAttribute('fill');
Update
Try something like this:
if (svgElement) {
var st24 = svgdom.getElementsByClassName("st24");
$.each(st24, function( i, val) {
val.removeAttribute("fill");
});
svgElement.setAttribute("fill", "#008000");
} else ...
Update 2
Have a look at this fiddle. Hopefully it should help explain what I mean.
http://jsfiddle.net/gt7nd/1/

Use this
$(val).css('fill',"#008000");
or this
val.style.fill = "#000800"

My SVG code:
<g id="505Б-1" place="place" v:mID="1937" v:groupContext="shape" transform="translate(206.929,-334.488)" class="test">
<title>Circle, ellipse.1937</title>
<v:userDefs>
<v:ud v:nameU="visVersion" v:val="VT0(14):26"/>
</v:userDefs>
<path transform="" d="M0 837.64 A4.25197 4.25197 0 0 1 8.5 837.64 A4.25197 4.25197 0 1 1 0 837.64 Z" class="st24"/>
</g>
I use class "test" instead "st24", and everything works now!

Related

Filter by value in checkbox popup in Mapbox GL

I have changed my mind about how I want to use the Checkbox filter in Mapbox. I am using CSV2Geojson to map Google Sheets data in my map and then filter by values in one column. I know there is this https://labs.mapbox.com/education/impact-tools/finder-with-filters/ but I want to stick to my layout instead of using a config file to define options. My original spreadsheet had a function that looked at column headers and only returned cells with "Y" in them when checked. Now, I have 1 column where I need to look for 4 specific values. Below is the code and codepen for debugging. The code in question is at the bottom of the code block.
https://codepen.io/bearcats6001/project/editor/AjrPPP
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>CodePen - project map 2</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<!-- partial:index.partial.html -->
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link href="https://api.mapbox.com/mapbox-gl-js/v2.7.0/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v2.7.0/mapbox-gl.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<script src='https://npmcdn.com/csv2geojson#latest/csv2geojson.js'></script>
<script src='https://npmcdn.com/#turf/turf/turf.min.js'></script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.7.2/mapbox-gl-geocoder.min.js"></script>
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.7.2/mapbox-gl-geocoder.css" type="text/css">-->
<div id="map">
<div id="filterMenu">
<h3>Programs</h3>
<input type="checkbox" id="Nathan" name="srBox" value="SustainableRecreation">
<label for="Nathan"> Nathan Shock Centers of Excellence in the Basic Biology of Aging</label><br>
<input type="checkbox" id="Pepper" name="hlBox" value="HealthyLandscapes">
<label for="Pepper"> Claude D. Pepper Older Americans Independence Centers</label><br>
<input type="checkbox" id="Aging" name="ovBox" value="Overnight">
<label for="Aging"> Centers on the Demography and Economics of Aging</label><br>
<input type="checkbox" id="Minority" name="ovBox" value="Overnight">
<label for="Minority"> Resource Centers for Minority Aging Research</label><br>
</div>
</div>
<!-- partial -->
<script src="./script.js"></script>
</body>
</html>
var transformRequest = (url, resourceType) => {
var isMapboxRequest =
url.slice(8, 22) === "api.mapbox.com" ||
url.slice(10, 26) === "tiles.mapbox.com";
return {
url: isMapboxRequest
? url.replace("?", "?pluginName=sheetMapper&")
: url,
};
};
mapboxgl.accessToken = 'pk.eyJ1IjoiYWZhcm9yZyIsImEiOiJjbDIwajV3YTUwMGc3M2xwNDdiYWJiMjUzIn0.Pjt9AndPk1Axv99wez-5TA';
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v10',
center: [-102.182698, 37.131563],
zoom: 3,
//left, bottom, right, top
});
var nav = new mapboxgl.NavigationControl({
showCompass: true,
showZoom: true,
visualizePitch: true
});
map.addControl(nav, "bottom-right");
$(document).ready(function () {
$.ajax({
type: "GET",
url: 'https://docs.google.com/spreadsheets/d/1umfhXq5WEPLEABV81-tZUayAw7WZrmqe/gviz/tq?tqx=out:csv&sheet=Sheet1',
dataType: "text",
success: function (csvData) { makeGeoJSON(csvData); }
});
function makeGeoJSON(csvData) {
csv2geojson.csv2geojson(csvData, {
latfield: 'Latitude',
lonfield: 'Longitude',
delimiter: ','
}, function (err, data) {
map.on('load', function () {
map.addLayer({
'id': 'rfovProjects',
'type': 'circle',
'source': {
'type': 'geojson',
'data': data
},
'paint': {
'circle-radius': 7,
'circle-color': "blue",
'circle-opacity': 0.5,
}
});
});
});
};
});
map.on('mouseenter', 'rfovProjects', function () {
map.getCanvas().style.cursor = 'pointer';
});
map.on('mouseleave', 'rfovProjects', function () {
map.getCanvas().style.cursor = '';
});
map.on('click', function(e) {
if(!e.originalEvent.defaultPrevented) {
e.originalEvent.preventDefault();
}
var features = map.queryRenderedFeatures(e.point, {
layers: ['rfovProjects']
});
if (!features.length) {
return;
}
var feature = features[0];
var popupContent = '<h3 style="display:inline">' + feature.properties.Name + '</h3><br><p style="display:inline"><b>'
/*popupContent += feature.properties.time ? '</b>, ' + feature.properties.time : '</b>'*/
popupContent += '<br> Website Link </p>'
var popup = new mapboxgl.Popup({ offset: [0, 0] })
.setLngLat(e.lngLat)
.setHTML(popupContent)
.addTo(map);
});
//basemap toggles
/*
var tRadio = document.getElementById('topoRadio');
tRadio.addEventListener('change', function() {
if (this.checked) {
map.setLayoutProperty('mapbox-satellite', 'visibility', 'none');
}
});
var iRadio = document.getElementById('imageryRadio');
iRadio.addEventListener('change', function() {
if (this.checked) {
map.setLayoutProperty('mapbox-satellite', 'visibility', 'visible');
}
});*/
//
map.doubleClickZoom.enable();
map.on('dblclick', function(e) {
map.getZoom() +10;
});
map.addControl(
new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
mapboxgl: mapboxgl,
flyTo: {
zoom: 12,
easing: function(t) {
return t;
}
},
marker: false
})
);
map.addControl(new mapboxgl.NavigationControl());
var filters = {};
function updateFilters() {
var compositeFilter = ['all'];
for (let filterValue in filters) {
if (filters[filterValue]) {
compositeFilter.push(['==', ['get', filterValue], 'Y']);
}
}
if (compositeFilter.length > 1)
map.setFilter('rfovProjects', compositeFilter);
else {
map.setFilter('rfovProjects', null);
}
}
var checkbox = document.getElementById('Nathan');
checkbox.addEventListener('change', function() {
filters['Program'] = this.checked;
updateFilters();
});
var checkbox = document.getElementById('Pepper');
checkbox.addEventListener('change', function() {
filters['Program'] = this.checked;
updateFilters();
});
var checkbox = document.getElementById('Aging');
checkbox.addEventListener('change', function() {
filters['Program'] = this.checked;
updateFilters();
});
var checkbox = document.getElementById('Minority');
checkbox.addEventListener('change', function() {
filters['Program'] = this.checked;
updateFilters();
});

Jquery UI appendTo NOT WORKING

Im trying to use jquery ui for search bar autocomplete. When I use div id="inputs" autocomplete works fine, but if I use input id="inputs" it's not working and i need to use input in order to search works properly.
(function ($) {
$.fn.googleSuggest = function(opts){
opts = $.extend({service: 'web', secure: false}, opts);
var services = {
web: { client: 'hp', ds: '' },
}, service = services[opts.service], span = $('<span>');
opts.source = function(request, response){
$.ajax({
url: 'http'+(opts.secure?'s':'')+'://clients1.google.com/complete/search',
dataType: 'jsonp',
data: {
q: request.term,
nolabels: 't',
client: service.client,
ds: service.ds
},
success: function(data) {
response($.map(data[1], function(item){
return { value: span.html(item[0]).text() };
}));
}
});
};
return this.each(function(){
$(this).autocomplete(opts);
});
}
}(jQuery));
$.each("web".split(" "), function(i, v){
var div = $("<div>").appendTo("#inputs")
, input = $("<input>").appendTo(div)
input.googleSuggest({ service: v });
});
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/ui-lightness/jquery-ui.css" type="text/css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div id="inputs"></div>
</body>
</html>
<input> tags can't have child elements, so you can't append nodes to them.
It looks like what you're trying to append is a div, which contains another input, which you run googleSuggest() against:
var div = $("<div>").appendTo("#inputs")
, input = $("<input>").appendTo(div)
input.googleSuggest({ service: v });
So it seems that you don't need to append anything. Instead, just put googleSuggest on the <input> that's already in the DOM:
$('#inputs').googleSuggest({ /*...*/ })

dgrid in a custom widget

I have a custom widget to which I pass data from backend. Grid shown on the correct place but not showing data on it. I tried with hardcoded data but only the headers are shown. Grid has height and width set.
Here is the code snippet. I would appreciate any help. thanks.
define(["dojo/_base/declare", "dijit/_WidgetBase",
"dijit/_TemplatedMixin", "dijit/_WidgetsInTemplateMixin",
"dijit/_OnDijitClickMixin",
GridWidget.js
define(["dojo/_base/declare", "dijit/_WidgetBase",
"dijit/_TemplatedMixin", "dijit/_WidgetsInTemplateMixin",
"dijit/_OnDijitClickMixin", "dojo/text!./templates/GridWidget.html",
"dgrid/Grid","dgrid/Keyboard", "dgrid/Selection", "dgrid/extensions/DijitRegistry", "dstore/Memory", "dstore/Trackable"], function(declare, _WidgetBase,
_TemplatedMixin, _WidgetsInTemplateMixin,
_OnDijitClickMixin, template, Grid, Keyboard, Selection, DigitRegistry, Memory, Trackable) {
return decalare("GridWidget", [_WidgetBase, _OnDijitClickMixin, _TemplatedMixin, _WidgetsInTemplateMixin], {
widgetsInTemplate: true,
baseClass: 'GridWidget',
templateString: template,
data: null,
store: null,
grid: null,
columns: null,
constructor: function(data) {
this.data = data;
},
_setData: function(input) {
if (input) {
this._set("data", input);
}
},
getData: function() {
return this.data;
},
postCreate : function() {
this.inherited(arguments);
var StandardGrid = declare([Grid, Selection, Keyboard, DijitRegistry]);
this.store = new (declare([Trackable, Memory]))({
data : this.data,
idProperty : "isbn"
});
this.columns = {
bookTitle : "Title",
first : "First Name",
last : "Last Name",
releaseDate : "Release Date"
};
this.grid = new StandardGrid({
collection : this.store,
columns : this.columns,
cellNavigation : false,
noDataMessage : "No results.",
loadingMessage : "Loading Data...",
}, this.gridNode);
}
startup: function() {
if (this._started) return;
this.inherited(arguments);
if (this.grid) {
this.grid.startup();
}
}
});
});
GridWidget.html
<div class="${baseClass}">
<div class="${baseClass}Grid"data-dojo-attach-point="gridNode"></div>
</div>
testGridWidget.html
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test: Dgrid 0.4</title>
<link rel="stylesheet" href="style.css" media="screen">
<link rel="stylesheet" href="dojo/dijit/themes/claro/claro.css" media="screen">
<script>
//var startTime = new Date();
var CONTEXT_ROOT = 'DtossApp';
var djConfig = (function(){
var base = location.href.split("/");
base.pop();
base = base.join("/");
return {
parseOnLoad: true,
isDebug: true,
packages: [{
name: CONTEXT_ROOT,
location: base + "/widget"
}]
};
})();
</script>
</head>
<body class="claro">
<script>
function showGrid() {
require([
CONTEXT_ROOT + '/GridWidget',
'dojo/dom-construct',
'dojo/dom',
'dijit/layout/ContentPane',
], function (GridWidget, domConstruct, dom, ContentPane) {
var testWidget = new GridWidget({ data: createData()});
var cp = new ContentPane({
title : "Book List",
content : testWidget});
var ref = dom.byId('grid');
domConstruct.place(cp.domNode, ref);
testWidget.startup();
//Copied from dgrid laboratory sample..
function createData () {
var data = [];
var column;
var i;
for (i = 0; i < 50; i++) {
data.push({});
for (column in { first: 1, last: 1, bookTitle: 1, releaseDate: 1 }) {
data[i].isbn = i;
data[i][column] = column + '_' + (i + 1);
}
}
return data;
}
});
}
</script>
<h1>Test: Dgrid 0.4</h1>
<div id="buttonContainer">
<button class="action" onClick="showGrid1()">Show Grid</button>
</div>
<div id="grid"></div>
<!-- load dojo and provide config via data attribute -->
<script src="dojo/dojo/dojo.js"></script>
</body>
</html>
GridWidget.css
.GridWidgetGrid {
height: 300px;
width: 80%;
}
Dgrid tutorial shows the following note:
When using the basic Grid module, the grid will be empty until you call renderArray. The more advanced store-based implementations like OnDemandGrid will populate themselves from the store automatically.
I changed my Grid to OnDemandGrid which picks data from store automatically.
Also calling renderArray in startup method populates data for Grid.

How to tell what has been destroyed by the destroy command in a kendo UI grid?

I'm using Kendo UI 2013.2.716 and JQuery 2.0.3 and I am placing a grid on my page, and my question is:
Does anyone know how to tell what has been destroyed by the destroy command from the grid?
For example:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link href="kendo.common.min.css" rel="stylesheet" />
<link href="kendo.default.min.css" rel="stylesheet" />
<script type="text/javascript" src="jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="kendo.all.min.js"></script>
</head>
<body>
<div id="grid"></div>
<script type="text/javascript">
$(document).ready(function() {
var products = [];
for(var i = 1; i <= 40; i++) {
products.push({
ProductId: i,
ProductName: "Product " + i
});
}
$("#grid").kendoGrid({
dataSource: {
data: products,
schema: {
model: {
id: "ProductId",
fields: {
ProductName: { type: "string" },
}
}
},
requestEnd: function (e) {
if (e.type === "destroy") {
alert("OK, so something got destroyed, but what??");
}
}
},
editable: "inline",
columns: [
"ProductName",
{ command: "destroy", title: " ", width: "100px" }
]
});
});
</script>
</body>
</html>
I found the requestEnd callback in the documentation but I am totally flummoxed as to know where the item that was destroyed would be. I just need the ID of the item really so that I can update other parts of my page appropriately.
I am wondering if I need to capture it somehow beforehand.
You need to configure the transport object on your datasource. In your current configuration, does anything really get destroyed? Sure, the item may disappear from your grid, but I wonder if it's still there in the datasource. Maybe that's what you intended.
http://docs.kendoui.com/api/framework/datasource#configuration-transport.destroy
If you're just looking for a way to get at the data that's being destroyed, hook into the parameterMap() function of the transport object. In there you can manipulate the object being deleted before the operation is executed.
http://docs.kendoui.com/api/framework/datasource#configuration-transport.parameterMap
Thanks to #Brett for pointing out the destroy property on the transport. This code does the trick - allowing me to capture what was being destroyed (see the transport.destroy part):
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link href="kendo.common.min.css" rel="stylesheet" />
<link href="kendo.default.min.css" rel="stylesheet" />
<script type="text/javascript" src="jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="kendo.all.min.js"></script>
</head>
<body>
<div id="grid"></div>
<script type="text/javascript">
$(document).ready(function() {
$("#grid").kendoGrid({
dataSource: {
schema: {
model: {
id: "ProductId",
fields: {
ProductName: { type: "string" },
}
}
},
transport: {
read: function (options) {
var products = [];
for(var i = 1; i <= 40; i++) {
products.push({
ProductId: i,
ProductName: "Product " + i
});
}
options.success(products);
},
destroy: function (options) {
var data = $("#grid")
.data("kendoGrid").dataSource.data();
var products = [];
for(var i = 0; i < data.length; i++) {
if (data[i].ProductId !== options.data.ProductId) {
products.push(data[i])
}
}
options.success(products);
alert("Woo hoo - the product with the ID: "
+ options.data.ProductId + " was destroyed!");
}
}
},
editable: "inline",
columns: [
"ProductName",
{ command: "destroy", title: " ", width: "100px" }
]
});
});
</script>
</body>
</html>

Javascript Variable Scope with KendoUI Components

I am trying to capture the text from a Kendo AutoComplete component and save it to a variable to later use in other components. The code is below and I have a link to the code at jsbin.com. Note: the code jsbin.com does not work for me in IE9, Firefox and Chrome work fine.
I attach my onSelect function fires when a selecton is made in the autoComplete control. I then assign the dataItem to my variable "selectedGeoname". I successfully write the object's text property to an element on screen and I use an alert to confirm that selectedGeoname is populated by the object.
However, when I later try to use the variable to pass the value to another component, the variable is null. I instantiate both components and declare the variable inside $(document)ready. I would have to believe that this is all ablout scope so perhaps one of you javascript wizards can help poor old .Net guy to fix this code.
Thanks,
Greg
HTML as follows:
<!DOCTYPE html>
<html>
<head>
<link href="http://cdn.kendostatic.com/2012.2.710/styles/kendo.common.min.css"
rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2012.2.710/styles/kendo.default.min.css"
rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2012.2.710/styles/kendo.dataviz.min.css"
rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2012.2.710/styles/kendo.mobile.all.min.css"
rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://cdn.kendostatic.com/2012.2.710/js/kendo.all.min.js"></script>
<title></title>
</head>
<body>
<p>
<label for="customer">Choose a customer:</label>
<input id="customer" />
<div id="result"></div>
</p>
<p>
<label for="stores">Choose a store:</label>
<input id="stores" />
</p>
<script type="text/javascript">
$(document).ready(function () {
$("#customer").kendoAutoComplete({
dataTextField: "name",
dataSource: {
serverFiltering: true,
transport: {
read: {
url: "http://ws.geonames.org/searchJSON",
dataType: "json",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: function () {
return $("#customer").val();
}
}
}
},
schema: {
data: "geonames"
}
},
filter: "startswith",
placeholder: "Select Customer...",
height: 500,
suggest: true,
select: onSelect
});
var selectedGeoname;
function onSelect(e) {
var dataItem = this.dataItem(e.item.index());
selectedGeoname = dataItem;
//output
$("#result").html(selectedGeoname.name);
alert(selectedGeoname);
}
$("#stores").kendoDropDownList({
autoBind: false,
enable: true,
dataTextField: "StoreName",
dataValueField: "StoreId",
dataSource: {
serverFiltering: true,
transport: {
read: {
url: '#Url.Action("JsonGetStores", "Home")',
data: {
customer: selectedGeoname
}
}
}
}
});
});
</script>
</body>
</html>
You can use this code as your onSelect to achieve this:
function onSelect(e) {
selectedGeoname = this.value();
//output
$("#result").html(selectedGeoname.name);
alert(selectedGeoname);
}
When called from the context of the AutoComplete object this.value() can be used to get the value of the AC input element.
If you need to access the current value of the variable outside of the scope you can use this method: $("#customer").data("kendoAutoComplete").value().
Hope this helps!

Categories