I am using google maps. And I can see the google map. But I get every this error:
SCRIPT5009: 'google' is undefined
My script is this:
var map;
if (typeof initMap == 'function') {
initMap();
}
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: { lat: 52.001321, lng: 4.374577 }
});
var geocoder = new google.maps.Geocoder();
document.getElementById('submit').addEventListener('click', function () {
geocodeAddress(geocoder, map);
});
}//end function initMap
$("document").ready(function () {
map = new google.maps.Map(document.getElementById('map'),
mapOptions);
});
//function loadScript() {
// var script = document.createElement('script');
// script.type = 'text/javascript';
// script.src = 'https://maps.googleapis.com/maps/api/js?v=3&sensor=false&callback=initMap';
// document.body.appendChild(script);
//}
//addLoadEvent(loadScript);
function toggleBounce() {
if (marker.getAnimation() !== null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
var marker;
var infowindow;
function geocodeAddress(geocoder, resultsMap) {
if (typeof infowindow != 'undefined') {
infowindow.close();
}
if (typeof marker != 'undefined') {
marker.setMap(null);
}
var address = document.getElementById('address').value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
resultsMap.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: resultsMap,
draggable: true,
animation: google.maps.Animation.DROP,
position: results[0].geometry.location,
title: "Drag me!"
});
//document.getElementById(marker.getPosition().lat().toFixed(6)).className += "geolocation_long";
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
infowindow = new google.maps.InfoWindow({
content: '<p>Marker Location:'
+ 'lat: ' + marker.getPosition().lat().toFixed(6)
+ ', '
+ 'lng: ' + marker.getPosition().lng().toFixed(6)
+ '</p>'
});
document.getElementById("form_inp17").value = marker.getPosition().lng().toFixed(6);
document.getElementById("form_inp18").value = marker.getPosition().lat().toFixed(6);
google.maps.event.addListener(marker, 'dragend', function (event) {
if (typeof infowindow != 'undefined') {
infowindow.close();
}
infowindow = new google.maps.InfoWindow({
content: '<p>Marker Location:'
+ 'lat: ' + event.latLng.lat().toFixed(6)
+ ', '
+ 'lng: ' + event.latLng.lng().toFixed(6)
+ '</p>'
});
document.getElementById("form_inp17").value = event.latLng.lng().toFixed(6)
document.getElementById("form_inp18").value = event.latLng.lat().toFixed(6)
infowindow.open(map, marker);
});
infowindow.open(map, marker);
google.maps.event.addListener(marker, 'click', function (event) {
if (typeof infowindow != 'undefined') {
infowindow.open(map, marker);
}
});
});
}
And my html page where I refer to the google maps is like this:
#{
Layout = "~/Areas/Form/Views/Shared/_RenderLayout.cshtml";
}
#section SFSHeadSection {
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/xforms")
#Scripts.Render("~/bundles/xforms_" + ViewBag.Locale)
#if (ViewBag.Includes != null){
#Scripts.Render(ViewBag.Includes);
}
<script src="https://maps.googleapis.com/maps/api/js?signed_in=true&callback=initMap" async defer type="text/javascript"></script>
<script type="text/javascript">
$(function () {
#Html.Raw(ViewBag.onloadscript)
});
</script>
#Styles.Render("~/Content/jquery-ui.css")
#Styles.Render("~/css/Geo-picker.css")
<style type="text/css">
#Html.Raw(ViewBag.style)
</style>
}
<div>
#Html.Raw(ViewBag.FormHtml)
</div>
Thank you
and yes, I already looked at this thread:
http://stackoverflow.com/questions/11940872/script5009-google-is-undefined
Related
I'm trying to invoke a javascript function in a Blazor component, but with no success.
The error is:
Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Could not find 'FullCalendarInterop.init' ('FullCalendarInterop' was undefined).
Error: Could not find 'FullCalendarInterop.init' ('FullCalendarInterop' was undefined).
at https://localhost:7065/_framework/blazor.webassembly.js:1:328
at Array.forEach ()
at a.findFunction (https://localhost:7065/_framework/blazor.webassembly.js:1:296)
at _ (https://localhost:7065/_framework/blazor.webassembly.js:1:2437)
at https://localhost:7065/_framework/blazor.webassembly.js:1:3325
at new Promise ()
Component structure:
Razor page:
#using Microsoft.JSInterop
#inject IJSRuntime JSRuntime
protected override async Task OnAfterRenderAsync(bool firstRender)
{
var options = new CalendarOptions
{
Id = Id,
DefaultView = View,
CalendarEvents = Events.Where(r => r.Status == CalendarEventStatus.Active).ToList()
};
var dotNetObjectReference = DotNetObjectReference.Create(this);
var fullCalendarInterop = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./Shared/InputCalendar.razor.js");
await fullCalendarInterop.InvokeVoidAsync("FullCalendarInterop.init", options, dotNetObjectReference);
// I already just tried^
// await JSRuntime.InvokeVoidAsync("FullCalendarInterop.init", options, DotNetObjectReference.Create(this));
await base.OnAfterRenderAsync(firstRender);}
Javascript
var FullCalendarInterop = function () {
return {
//main function to initiate the module
init: function (options, dotNetReference) {
var calendarEl = document.getElementById(options.id);
var calendar = new window.FullCalendar.Calendar(calendarEl, {
plugins: ['interaction', 'dayGrid', 'timeGrid', 'list'],
isRTL: window.KTUtil.isRTL(),
header: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
},
height: 800,
contentHeight: 750,
aspectRatio: 3, // see: https://fullcalendar.io/docs/aspectRatio
views: {
dayGridMonth: { buttonText: 'month' },
timeGridWeek: { buttonText: 'week' },
timeGridDay: { buttonText: 'day' },
listWeek: { buttonText: 'list' }
},
defaultView: options.defaultView,
defaultDate: options.defaultDate,
editable: true,
eventLimit: true, // allow "more" link when too many events
navLinks: true,
events: options.calendarEvents,
eventRender: function (info) {
var event = $(info.event);
var element = $(info.el);
var view = $(info.view);
if (info.event.extendedProps && info.event.extendedProps.description) {
if (element.hasClass('fc-day-grid-event')) {
element.data('content', info.event.extendedProps.description);
element.data('placement', 'top');
window.KTApp.initPopover(element);
} else if (element.hasClass('fc-time-grid-event')) {
element.find('.fc-title').append('<div class="fc-description">' + info.event.extendedProps.description + '</div>');
} else if (element.find('.fc-list-item-title').lenght !== 0) {
element.find('.fc-list-item-title').append('<div class="fc-description">' + info.event.extendedProps.description + '</div>');
}
}
element.find(".fc-bg").css("pointer-events", "none");
element.find(".fc-list-item-title.fc-widget-content").prepend(
"<span style='position: absolute; right: 5px;'>" +
"<button class='btn btn-icon btn-xs btn-circle btn-light' " +
"style='height: 16px; width: 16px;' id='calendar_del_" + event.id + "'>" +
"<i class='icon-xs text-dark-50 flaticon2-cross'></i></button></span>");
element.find(".fc-content").append("<span style='position: absolute; top: 5px; right: 5px;'>" +
"<button class='btn btn-icon btn-xs btn-circle btn-light' " +
"style='height: 16px; width: 16px;' id='calendar_del_" + event.id + "'>" +
"<i class='icon-xs text-dark-50 flaticon2-cross'></i></button></span>");
element.find("#calendar_del_" + event.id).click(function () {
var eventId = event[0]._def.defId;
var eventIdentifier = event[0]._def.extendedProps.identifier;
//Remove popover
removeContent(".popover.fade.show.bs-popover-top");
//$(".popover.fade.show.bs-popover-top").remove();
dotNetReference.invokeMethodAsync('CalendarEventDeleted', eventIdentifier);
//$("#candidate_calendar").fullCalendar('removeEvents', eventId);
});
},
viewSkeletonRender: function (info) {
var view = $(info.view);
var defaultView = view[0].type !== null ? view[0].type : "";
dotNetReference.invokeMethodAsync('SetDefaultView', defaultView);
//alert(defaultView);
}
});
calendar.render();
}
};
}
Modify your .JS file like so:
var FullCalendarInterop = function () {
return {
//main function to initiate the module
init: function (options, dotNetReference) {
... Trimmed for brevity ...
calendar.render();
}
};
}();
export { FullCalendarInterop };
I added (); to the end of your FullCalendarInterop function and then added the export. That should work for you.
As it says its a null reference error as you are not initializing JSmodule,
IJSObjectReference fullCalendarInterop;
fullCalendarInterop = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./Shared/InputCalendar.razor.js");
trying to solve IE issue where by the Google map is rendered incorrect an in google chrome and Firefox is fine, below is the image of how it is displaying in IE:
I will be happy if you can help me solve this issue.
Here is my code
$(document).ready(function () {
jQuery('#PropertySearchMap').css({
"position": "absolute !important",
"left": "-10000px !important"
});
if ($('#PropertySearchMap').is(':visible')) {
setTimeout(function () {
Initialize()
}, 500);
jQuery('#PropertySearchMap').show();
jQuery('#PropertySearchMap').css({
"position": "static !important"
});
}
});
function Initialize() {
$("#butSearch").click(function (e) {
ls.mapping.search();
e.preventDefault();
});
$("#butReset").click(function (e) {
var loc = document.location.href.toString().split("#");
document.location = loc[0];
});
$("#butAdd").click(function (e) {
parent.$("#Model.Source.GetTag()").trigger("property:selected", {
propertyId: 0
});
});
$("footer").hide();
$('#select_all').click(function () {
var c = this.checked;
$(':checkbox').prop('checked', c);
});
$(".body-content").css("height", "100%");
$(".body-content").css("width", "100%");
ls.rootUrl = "#System.Configuration.ConfigurationManager.AppSettings["
PropertyServiceUrl "]";
ls.mapping.initiAutoComplete();#
if (Model.DisableMap) {#: ls.mapping.disableClickSearch = true;
}#
if (Model.HideSearchControls && Model.DisableMap) {#: ls.mapping.initializeMap(true);
} else {#: ls.mapping.initializeMap(false);
}# if (Model.Source == MapSourceEnum.CompSales) {
//#:window.setTimeout(ls.mapping.plotCompsales, 1000); Stephan - verify this is required
#: ls.mapping.plotCompsales();
}# {#: ls.mapping.propertySelectedEventTarget = "#Model.Source.GetTag()";
}
ls.tools.initToolFuncs();
}
Starting from here: How do I display a Json random number in a real-time Flot chart?, I managed to display a random number on a flot chart. The x axes is the current time's second. The problem I have is that now on my chart is shown only a point (current value). What I want is to display a real time line according to the values of the random number. How could I do this? I hope I made myself understood.
Here is my cod:
In C#:
if (method == "rnd")
{
//Current second
this.Page.Response.ContentType = "application/json1";
DateTime now = DateTime.Now;
int sec = now.Second;
Random rnd = new Random();
int nr = rnd.Next(1, 100); // creates a number between 1 and 99
var str = "{\"sec\":" + sec.ToString() + ",\"val\":" + nr.ToString() + "}";
var json2 = new JavaScriptSerializer().Serialize(str);
this.Page.Response.Write(json2);
}
My ASP page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="MultiTrenduri.aspx.cs" Inherits="WebApplication2.MultiTrenduri" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.8.3.min.js"></script>
<script src="Scripts/flot/jquery.flot.min.js"></script>
<script src="Scripts/flot/jquery.flot.time.js"></script>
<script src="Scripts/flot/jquery.flot.symbol.js"></script>
<script src="Scripts/flot/hashtable.js"></script>
<script src="Scripts/flot/jquery.flot.axislabels.js"></script>
<script src="Scripts/flot/jquery.numberformatter-1.2.3.min.js"></script>
<link href="Flot/examples.css" rel="stylesheet" />
<script type="text/javascript">
var sc = [], num = [];
function test2() {
$.ajax({
type: 'POST',
url: ('ajax.aspx?meth=') + "rnd",
contentType: 'application/json2; charset=utf-8',
dataType: 'json',
async: true,
cache: false,
global: false,
timeout: 120000,
success: function (data, textStatus, jqXHR) {
var obj = jQuery.parseJSON(data);
$('#azi').html(obj.sec);
$('#nr').html(obj.val);
var sc = [], num = [];
sc.push(obj.sec);
num.push(obj.val);
data = [[[sc, num]]];
//var afis = [[[data]]];
//$('#afs').text(afis.join(" * "));
//show the data in a list in body
var items = [];
$.each(data, function (key, val1) {
items.push("<li><a href=#'" + key + "'>" + val1 + "</a></li>");
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
//START: PLOT IN TIMP REAL
$(function () {
var plot = $.plot("#placeholder", data,
{
series: {
shadowSize: 0 // Drawing is faster without shadows
},
points: { show: true },
line: { show: true },
yaxis: {
min: 0,
max: 100
},
xaxis: {
show: true
}
});
// plot.setData(data); //to reset data
// plot.draw(); //to redraw chart
});
// plot.draw();
//END: PLOT IN TIMP REAL
},
error: function (jqXHR, textStatus, errorThrown) {
window.alert(errorThrown);
}
});
}
window.setInterval(test2, 1000);
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="azi"></div>
<div id="nr"></div>
<div class="demo-container">
<div id="placeholder" class="demo-placeholder">
</div>
</div>
</div>
</form>
</body>
</html>
Maybe is someone which needs to do the same. This is how I managed to do it.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script src="Scripts/jquery-1.8.3.min.js"></script>
<script src="Scripts/flot/jquery.flot.min.js"></script>
<script src="Scripts/flot/jquery.flot.time.js"></script>
<script src="Scripts/flot/jquery.flot.symbol.js"></script>
<script src="Scripts/flot/hashtable.js"></script>
<script src="Scripts/flot/jquery.flot.axislabels.js"></script>
<script src="Scripts/flot/jquery.numberformatter-1.2.3.min.js"></script>
<link href="Flot/examples.css" rel="stylesheet" />
<%-- Library for TOOLTIP:--%>
<script src="Scripts/flot/jquery.flot.crosshair.js"></script>
<!-- CSS -->
<%--<style type="text/css">
#placeholder {
width: 1000px;
height: 500px;
text-align: center;
margin: 0 auto;
}
</style>--%>
<%-- <link href="Flot/examples.css" rel="stylesheet" />--%>
<%-- <script src="Scripts/jquery-1.4.1.js"></script>
<script src="Scripts/flot/jquery.flot.js"></script>--%>
<script type="text/javascript">
var sc = [], num = [];
var data = [];
var dataset;
var totalPoints = 100;
var updateInterval=30 ;
var now = new Date().getTime();
var t;
var multipleCalls, multCalls;
var input = document.getElementById('input');
var st;
/* window.onload = function f1() {
document.getElementById('updateInterval').value = 90;
}
function f2() {
// document.getElementById('up2').value = document.getElementById('up1').value
var updateInterval = document.getElementById('updateInterval').value;
// window.alert(updateInterval);
}*/
$(function () {
function test2() {
$.ajax({
type: 'GET',
url: ('ajax.aspx?meth=') + "rnd",
contentType: 'application/json2; charset=utf-8',
dataType: 'json',
//async: true,
//cache: false,
//global: false,
// timeout: 120000,
success: function (data, textStatus, jqXHR) {
var obj = jQuery.parseJSON(data);
$('#azi').html(obj.sec);
$('#nr').html(obj.val);
t = obj.val;
},
error: function (jqXHR, textStatus, errorThrown) {
window.alert(errorThrown);
}
});
}
function apel() {
test2();
$('#fn').html(t);
updateInterval = document.getElementById('updateInterval').value;
}
function GetData() {
data.shift();
data.slice(1);
while (data.length < totalPoints) {
// var y = Math.random() * 100;
var y = t;
var temp = [now += updateInterval, y];
data.push(temp);
}
}
$("#up").val(updateInterval).change(function () {
var vv = $(this).val();
if (vv && !isNaN(+vv)) {
updateInterval = +vv;
if (updateInterval < 1) {
updateInterval = 1;
} else if (updateInterval > 2000) {
updateInterval = 2000;
}
$(this).val("" + updateInterval);
}
});
var options = {
series: {
lines: {
show: true,
lineWidth: 1.2,
fill: false
}
},
xaxis: {
mode: "time",
tickSize: [2, "second"],
tickFormatter: function (v, axis) {
var date = new Date(v);
if (date.getSeconds() % 5 == 0) {
var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
var w = hours + ":" + minutes + ":" + seconds;
return w;
} else {
return "";
}
},
axisLabel: "Time",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 10
},
grid: {
hoverable: true,
clickable: true
},
yaxis: {
min: 0,
max: 100,
tickSize: 5,
tickFormatter: function (v, axis) {
if (v % 10 == 0) {
return v + "%";
} else {
return "";
}
},
axisLabel: "CPU loading",
axisLabelUseCanvas: true,
axisLabelFontSizePixels: 12,
axisLabelFontFamily: 'Verdana, Arial',
axisLabelPadding: 6
},
legend: {
labelBoxBorderColor: "#fff"
}
};
//START TOOLTIP
/* $("#placeholder").bind("plothover", function (event, pos, item) {
if ($("#enablePosition:checked").length > 0) {
var str = "(" + pos.x.toFixed(2) + ", " + pos.y.toFixed(2) + ")";
$("#hoverdata").text(str);
}
if ($("#enableTooltip:checked").length > 0) {
if (item) {
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
$("#tooltip").html(item.series.label + " of " + x + " = " + y)
.css({ top: item.pageY + 5, left: item.pageX + 5 })
.fadeIn(200);
} else {
$("#tooltip").hide();
}
}
});
$("#placeholder").bind("plotclick", function (event, pos, item) {
if (item) {
$("#clickdata").text(" - click point " + item.dataIndex + " in " + item.series.label);
plot.highlight(item.series, item.datapoint);
}
});
*/
//END TOOLTIP
st = $(document).ready(function f1() {
test2();
GetData();
dataset = [
{ label: "CPU", data: data }
];
$.plot($("#placeholder"), dataset, options);
function stop() {
//window.alert("Stop");
//multipleCalls.clearTimeout();
window.clearTimeout(updateInterval);
}
function update() {
test2();
GetData();
$.plot($("#placeholder"), dataset, options)
multipleCalls = setTimeout(update, updateInterval);
multCalls = multipleCalls;
}
update();
});
});
</script>
</head>
<body>
//Stops the graph
<button onclick="clearInterval(multipleCalls)">Stop</button>
<div id="header">
<div id="azi"></div>
<div id="nr"></div>
</div>
<div id="content">
<div class="demo-container">
<div id="placeholder" class="demo-placeholder"></div>
</div>
<p>Time between updates: <input id="up" type="text" value="" style="text-align: right; width:5em"/> milliseconds</p>
</div>
</body>
</html>
Source Code aspx page:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function loadData(e) {
e.preventDefault();
var ltlng = [];
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/getData",
dataType: "json",
success: function (data) {
$(data.d).each(function (index, item) {
var firstValue = parseFloat(item.FirstValue).toFixed(2);
var secondValue = parseFloat(item.SecondValue).toFixed(2);
ltlng.push(new google.maps.LatLng(firstValue, secondValue));
});
},
error: function () {
alert("Error");
}
});
//alert("Test");
markicons(ltlng);
}
var map; var infowindow;
function InitializeMap() {
var latlng = new google.maps.LatLng(40.756, -73.986);
var myOptions =
{
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
}
function markicons(ltlng) {
InitializeMap();
map.setCenter(ltlng[0]);
for (var i = 0; i <= ltlng.length; i++) {
if (ltlng[i] != undefined) {
marker = new google.maps.Marker({
map: map,
position: ltlng[i]
});
alert(ltlng[i]);
(function (i, marker) {
google.maps.event.addListener(marker, 'click', function () {
if (!infowindow) {
infowindow = new google.maps.InfoWindow();
}
infowindow.setContent("Message" + i);
infowindow.open(map, marker);
});
})(i, marker);
}
else {
}
}
}
window.onload = loadData;
</script>
<div id="map" style="width: 800px; height: 500px;">
</div>
Source Code for C#:
[WebMethod]
public static object getData()
{
var obj = new { FirstValue = 17.22, SecondValue = 78.28 };
var objList = (new[] { obj }).ToList();
objList.Add(new { FirstValue = 13.5, SecondValue = 79.2 });
objList.Add(new { FirstValue = 15.24, SecondValue = 77.16 });
return objList;
}
I am getting the result like this,
Tested Browser : Google Chrome. Please suggest me how can i resolve from this error.
You are calling your markicons(ltlng); method after you initialize your ajax request for the data.
You need to call this method AFTER you have got your data back.
Example:
success: function (data) {
$(data.d).each(function (index, item) {
var firstValue = parseFloat(item.FirstValue).toFixed(2);
var secondValue = parseFloat(item.SecondValue).toFixed(2);
ltlng.push(new google.maps.LatLng(firstValue, secondValue));
});
// Call method here.
markicons(ltlng);
},
I am using http://jqueryui.com/autocomplete/#combobox for my dropdownlist and it works well.
My problem here is when I disable the dropdown list from code behind it doesn't work.
My code is here.
ASPX
<asp:DropDownList runat="server" CssClass="Dropdown" ID="ddlStatus"> </asp:DropDownList>
JS
function pageLoad() {
/******** Auto Complete *********************/
$(function () {
$("#<%= ddlStatus.ClientID %>").combobox();
});
(function ($) {
$.widget("custom.combobox", {
_create: function () {
this.wrapper = $("<span>")
.addClass("custom-combobox")
.insertAfter(this.element);
this.element.hide();
this._createAutocomplete();
this._createShowAllButton();
},
_createAutocomplete: function () {
var selected = this.element.children(":selected"),
value = selected.val() ? selected.text() : "";
this.input = $("<input>")
.appendTo(this.wrapper)
.val(value)
.attr("title", "")
.addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy(this, "_source")
})
.tooltip({
tooltipClass: "ui-state-highlight"
});
this._on(this.input, {
autocompleteselect: function (event, ui) {
ui.item.option.selected = true;
this._trigger("select", event, {
item: ui.item.option
});
__doPostBack('<%= upnlTab.ClientID %>', this.element.attr("id"));
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function () {
var input = this.input,
wasOpen = false;
$("<a>")
.attr("tabIndex", -1)
//.attr("title", "Show All Items")
//.tooltip()
.appendTo(this.wrapper)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("custom-combobox-toggle ui-corner-right")
.mousedown(function () {
wasOpen = input.autocomplete("widget").is(":visible");
})
.click(function () {
input.focus();
// Close if already visible
if (wasOpen) {
return;
}
// Pass empty string as value to search for, displaying all results
input.autocomplete("search", "");
});
},
_source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(this.element.children("option").map(function () {
var text = $(this).text();
if (this.value && (!request.term || matcher.test(text)))
return {
label: text,
value: text,
option: this
};
}));
},
_removeIfInvalid: function (event, ui) {
// Selected an item, nothing to do
if (ui.item) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children("option").each(function () {
if ($(this).text().toLowerCase() === valueLowerCase) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if (valid) {
return;
}
// Remove invalid value
if (value != '') {
this.input
.val("")
.attr("title", value + " didn't match any item")
.tooltip("open");
this.element.val("");
this._delay(function () {
this.input.tooltip("close").attr("title", "");
}, 2500);
this.input.data("ui-autocomplete").term = "";
} else {
this.input.val("");
this.element.val("");
this.input.data("ui-autocomplete").term = "";
}
__doPostBack('<%= upnlTab.ClientID %>', this.element.attr("id"));
},
_destroy: function () {
this.wrapper.remove();
this.element.show();
}
});
})(jQuery);
}
C#
Based some validations I am calling this,
ddlStatus.Enabled = false;
There is an answer here and I am not be to get it work with my code.
Disable jQuery ComboBox when underlying DropDownList is disabled
This is how I have done it. please see the changes enclosed in * *.
(function ($) {
$.widget("custom.combobox", {
_create: function () {
this.wrapper = $("<span>")
.addClass("custom-combobox")
.insertAfter(this.element);
this.element.hide();
*select = this.element.hide();*
this._createAutocomplete(*select*);
this._createShowAllButton(*select*);
},
_createAutocomplete: function (*select*) {
var selected = this.element.children(":selected"),
select = this.element.hide(),
value = selected.val() ? selected.text() : "";
*var disabled = select.is(':disabled');*
this.input = $("<input>")
.appendTo(this.wrapper)
.val(value)
.attr("title", "")
.addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
.*attr('disabled', disabled)*
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy(this, "_source")
})
.tooltip({
tooltipClass: "ui-state-highlight"
});
this._on(this.input, {
autocompleteselect: function (event, ui) {
ui.item.option.selected = true;
this._trigger("select", event, {
item: ui.item.option
});
__doPostBack('<%= upnlTab.ClientID %>', this.element.attr("id"));
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function (*select*) {
var input = this.input,
wasOpen = false;
*var disabled = select.is(':disabled');*
console.log(this.element.attr("id") + " : " + disabled);
$("<a>")
.attr("tabIndex", -1)
*.attr('disabled', disabled)*
//.attr("title", "Show All Items")
//.tooltip()
.appendTo(this.wrapper)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("custom-combobox-toggle ui-corner-right")
.mousedown(function () {
wasOpen = input.autocomplete("widget").is(":visible");
})
.click(function () {
*if ($(this).attr('disabled')) {
return false;
}*
input.focus();
// Close if already visible
if (wasOpen) {
return;
}
// Pass empty string as value to search for, displaying all results
input.autocomplete("search", "");
});
},
_source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(this.element.children("option").map(function () {
var text = $(this).text();
if (this.value && (!request.term || matcher.test(text)))
return {
label: text,
value: text,
option: this
};
}));
},
_removeIfInvalid: function (event, ui) {
// Selected an item, nothing to do
if (ui.item) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children("option").each(function () {
if ($(this).text().toLowerCase() === valueLowerCase) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if (valid) {
return;
}
// Remove invalid value
if (value != '') {
this.input
.val("")
.attr("title", value + " didn't match any item")
.tooltip("open");
this.element.val("");
this._delay(function () {
this.input.tooltip("close").attr("title", "");
}, 2500);
this.input.data("ui-autocomplete").term = "";
} else {
this.input.val("");
this.element.val("");
this.input.data("ui-autocomplete").term = "";
}
__doPostBack('<%= upnlTab.ClientID %>', this.element.attr("id"));
},
_destroy: function () {
this.wrapper.remove();
this.element.show();
}
});
})(jQuery);