Disable Jquery autocomplete dropdown from codebehind c# - c#

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);

Related

Cascading (Dependent) DropDownList using ASP.NET MVC

I have implemented Cascading (Dependent) DropDownList using ASP.NET MVC.
This is the tutorial
Now I need show alert message box after insert data and redirect on Index page in ASP.NET MVC.
To show alert message in ASP.NET MVC after insert data using store procedure from MySQL database, I have write the code like as shown below.
<script type="text/javascript">
$(function () {
var msg = '#ViewData["result"]';
if (msg > 0)
{
alert("User Details Inserted Successfully");
window.location.href = "#Url.Action("Index", "Home")";
}
});
</script>
The data is correctly registered in the database table and the alert message box after insert data it's show.
But the redirect to index.cshtml not working because all the DropDownList on the form are empty except the first DropDownList that populates correctly.
window.location.href = "#Url.Action("Index", "Home")";
I mean that all other (populated cascading) DropDownList are enabled but empty.
I need redirect to Index Action page and being able to reload a new record, with this redirection it is impossible because the populated cascading DropDownList remain empty... instead of disabled and populated from value of first dropdownlist...
How to do resolve this?
Thanks.
Update 2021-01-02
#section Scripts {
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/Scripts/DatePicker.js");
#Styles.Render("~/Content/cssjqryUi")
<script type="text/javascript">
$(function () {
var msg = '#ViewData["result"]';
console.log(msg);
if (msg > 0)
{
alert("User Details Inserted Successfully");
var url = "#Url.Action("Index", "Home")";
window.location.href = url;
}
});
</script>
<script src="Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
jQuery(function ($) {
$.validator.addMethod('date',
function (value, element) {
if (this.optional(element)) {
return true;
}
var ok = true;
try {
$.datepicker.parseDate('dd/mm/yy', value);
}
catch (err) {
ok = false;
}
return ok;
});
$("#thedate").datepicker(options);
$(function () {
$(".loading").hide();
$("select").each(function () {
if ($(this).find("option").length <= 1) {
$(this).attr("disabled", "disabled");
}
});
$("select").change(function () {
var value = 0;
if ($(this).val() != "") {
value = $(this).val();
}
var id = $(this).attr("id");
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: '{type: "' + id + '", value: "' + value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var dropDownId;
var list;
switch (id) {
case "CountryId":
list = response.States;
DisableDropDown("#TicketId");
DisableDropDown("#CityId");
dropDownId = "#TicketId";
list = response.Ticket;
PopulateDropDown("#TicketId", list);
break;
case "TicketId":
list = response.States;
DisableDropDown("#StateId");
PopulateDropDown("#StateId", list);
break;
case "StateId":
dropDownId = "#CityId";
list = response.Cities;
DisableDropDown("#CityId");
PopulateDropDown("#CityId", list);
dropDownId = "#CityId2";
list = response.Cities2;
PopulateDropDown("#CityId2", list);
$("#GPS").val(response.GPS);
break;
}
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
function DisableDropDown(dropDownId) {
$(dropDownId).attr("disabled", "disabled");
$(dropDownId).empty().append('<option selected="selected" value="">[ === Select === ]</option>');
}
function PopulateDropDown(dropDownId, list) {
var modal = $('<div />');
modal.addClass("modalBackground");
$('body').append(modal);
var loading = $(".loading");
loading.show();
var top = Math.max($(window).height() / 2 - loading[0].offsetHeight / 2, 0);
var left = Math.max($(window).width() / 2 - loading[0].offsetWidth / 2, 0);
loading.css({ top: top, left: left });
setTimeout(function () {
if (list != null && list.length > 0) {
$(dropDownId).removeAttr("disabled");
$.each(list, function () {
$(dropDownId).append($("<option></option>").val(this['Value']).html(this['Text']));
});
$(".loading").hide();
$('.modalBackground').remove();
}
}, 1000);
}
</script>
}
update controller
[HttpPost]
public ActionResult Index(PersonModel person)
{
MTsqlinsert(person); //Insert values in the database
if (ModelState.IsValid)
{
PersonModel personModel = new PersonModel();
person.Countries = PopulateDropDown("SELECT CountryId, CountryName FROM Countries", "CountryName", "CountryId");
person.States = PopulateDropDown("SELECT StateId, StateName FROM States WHERE CountryId = " + countryId, "StateName", "StateId");
person.Cities = PopulateDropDown("SELECT CityId, CityName FROM Cities WHERE StateId = " + stateId, "CityName", "CityID");
ViewData["result"] = "1";
return RedirectToAction("Index");
}
return View(person);
}
[HttpGet]
[OutputCache(NoStore = true, Duration = 60, VaryByParam = "*")]
public ActionResult Index()
{
PersonModel personModel = new PersonModel
{
Countries = PopulateDropDown("SELECT CountryId, CountryName FROM Countries", "CountryName", "CountryId");
};
return View(personModel);
}

How to solve IE display google map incorrectly using iframe

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();
}

SCRIPT5009: 'google' is undefined google maps

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

ReferenceError:event is not defined

In my asp.net mvc3 page, i am using jquery to show a calender to display the events added in the database. Its working fine in google chrome but its showing below error in firefox 19.0.2
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery-1.8.3.js")"> </script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-i.css">
<link rel="stylesheet" href="../../Content/css/styleui.css" />
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("/Page/dates", null, function (data) {
var s = eval(data);
alert(s);
showevents(s);
});
function showevents(events) {
$("#datepicker").datepicker({
beforeShowDay: function (date) {
var result = [true, '', null];
var matching = $.grep(events, function (event) {
return event.Date.valueOf() === date.valueOf();
});
if (matching.length) {
result = [true, 'highlight', event.Title];
}
return result;
},
onSelect: function (dateText) {
var date, selectedDate = new Date(dateText), i = 0, event = null;
while (i < events.length && !event) {
date = events[i].Date;
if (selectedDate.valueOf() === date.valueOf()) {
event = events[i];
}
i++;
}
if (event) {
//return [true, "Highlighted", event.Title];
alert(event.Title);
}
}
});
}
});
</script>
<div id="datepicker">
[16:35:16.336] ReferenceError: event is not defined # http://code.jquery.com/jquery-1.8.3.js:579
You are probably missing var event; at the start of showevents function. See comments:
beforeShowDay: function (date) {
var result = [true, '', null];
var matching = $.grep(events, function (event) {
return event.Date.valueOf() === date.valueOf();
});
if (matching.length) {
// event is not defined
result = [true, 'highlight', event.Title];
}
return result;
},
onSelect: function (dateText) {
var date, selectedDate = new Date(dateText), i = 0, event = null;
while (i < events.length && !event) {
date = events[i].Date;
if (selectedDate.valueOf() === date.valueOf()) {
// event is not defined
event = events[i];
}
i++;
}
if (event) {
//return [true, "Highlighted", event.Title];
// event is not defined
alert(event.Title);
}
}

Adding jquery click event for UpdatePanel

I am using this code for binding asp.net gridview with right click contextmenu using jQuery but every time when I click it (use option in menu list) it reloads the page. What should I do if I want to use an UpdatePanel?
function fnView() {
var lnkView = document.getElementById('<%=lnkView.ClientID %>');
var hiddenField = document.getElementById('<%=fldProductID.ClientID %>');
hiddenField.value = $("div").filter("[type=ContextMenu]")[0].id.replace("Menu", "");
lnkView.click();
}
function fnDelete() {
var lnkDelete = document.getElementById('<%=lnkDelete.ClientID %>');
var hiddenField = document.getElementById('<%=fldProductID.ClientID %>');
hiddenField.value = $("div").filter("[type=ContextMenu]")[0].id.replace("Menu", "");
lnkDelete.click();
}
jQuery.fn.setEvents = function (e) {
var me1 = jQuery(this);
return this.each(function () {
var me = jQuery(this);
me.click(function (e) {
$("div").filter("[type=ContextMenu]").hide();
fnSetMenu(me.children(':first-child').text(), e.pageX, e.pageY);
});
});
};
function fnSetMenu(productID, left, top) {
if ($("#Menu" + productID).html() == null) {
var strMenuHTML = "<div type=\"ContextMenu\" id=\"Menu" + productID + "\" class=\"contextMenuClass\" mouseonmenu=\"1\"><table style='width:100%;'><tr><td onclick=fnView()>View Product</td></tr><tr><td onclick=fnDelete()>Delete Product</td></tr></table></div>";
$("body").append(strMenuHTML);
$.post("MenuHandler.ashx", {}, function (response) {
$("#Menu" + productID).html(response);
});
}
$("#Menu" + productID).css({ top: top + "px", left: left + "px" }).show();
}
$(document).ready(function () {
$("#gvProducts tr.ShowContext").setEvents();
}
);
$(document).click(function (e) {
$clicked = $(e.target);
if (!($clicked.parents().hasClass("ShowContext") || $clicked.hasClass("contextMenuClass") || $clicked.parents().hasClass("contextMenuClass"))) {
$("div").filter("[type=ContextMenu]").hide();
}
});
use jQuery's live function to bind an event inside updatepanel
or
go through this link
http://stackoverflow.com/questions/256195/jquery-document-ready-and-updatepanels

Categories

Resources