jQuery DoubleSelect/Cascade/Dependent/WalkRight Select Menus w/ Ajax Support? - jquery-plugins

Where you can pick an item from a <select> menu and then it populates a second <select> menu.
It goes by too many names and there are too many implementations. I'm looking for an up-to-date one (works well with the latest version of jQuery) that can pull the data using Ajax.
Can anyone recommend a good plugin?

// simple code but can be improved for need
function getListBoxValue(obj) {
obj = $.extend({
url: "",
bindObj: null,
emptyText: "exception",
postValues : {},
onComplete: function () { return true; },
onError: function () { return false; }
}, obj);
$.ajax({
url: obj.url,
data: obj.postValues,
type: "POST",
dataType: "JSON",
success: function (json) {
var options;
$.each(json, function (i, e) {
options += "<option value='" + e.Value + "'>" + e.Text + "</option>";
});
$(obj.bindObj).html(options);
obj.onComplete(obj);
},
error: function (e, xhr) {
$(obj.bindObj).html("<option value='-1'>" + obj.emptyText + "</option>");
obj.onError(obj);
}
});
}
// server response data json
[{ "Value": 1, "Text": "text 1 " },{ "Value": 2, "Text": "text 2"}]
getListBoxValue({
url: responseJsonDataURL, // example
bindObj: $("select#YourID"), // example
emptyText:"exception text", // example
postValues: {"id": 45}, // example
onComplete: _onCompleteFunction, // optional
onError: _onErrorFunction // optional
})

Related

Use select2 ajax data to update hidden inputs

I am having trouble updating hidden inputs using data retrieved from Select2 Ajax.
Please see my code:
var select2_town = $('.select-test select').select2({
ajax: {
url : ajax_var.url,
dataType: 'json',
type: 'post',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page,
};
},
processResults: function (data, page) {
return {
results: $.map(data, function (item) {
return {
id: item.id, //eg 1149
town: item.place_name, //eg Reading
county: item.county, //eg Berkshire
country: item.country,
data: item
};
})
};
},
cache: true;
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
templateResult: function (item) { return ('<p>' + item.town + ' - ' + item.county + '</p>'); },
templateSelection: function (item) { return (item.town); },
});
This code works fine for me. My issue is what happens after a value is selected.
I would like to update my hidden input ids "#town","#county" and "#country" with town,county and country respectively through an 'change' event.
I have seen many SO examples but they all stop at $(this).select2('data')[0];but do not expand on it.
Weird thing is that the following script displays the correct value in console log. but ALWAYS only apply the object id to #country.
select2_town.on('change', function() {
var obz = $(this).select2('data')[0].country;
console.log(obz);//displays Reading in console
$("#country").attr("value",obz); //displays 1149
});
This actually works.
I had another function that was adding the ID hidden in another file. I deleted that and then the script worked as I wanted it to.
Regards
Thanks

serialize json data from nhibernate

I know there are a couple threads on this but none of them have solved my issue. I'm trying to pull data from a ms sql db via Fluent nHibernate and serialize it to json data to the front end. Here is my nHibernate code:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetClans()
{
string output = string.Empty;
IList<Clan> clans = Counter.Strike.Database.Clan.GetAllClans();
Clan[] clanJson = new Clan[clans.Count];
for (int i = 0; i < clans.Count; i++ )
{
clanJson[i] = new Clan();
clanJson[i].Clan_Id = clans[i].Clan_Id;
clanJson[i].Clan_Name = clans[i].Clan_Name;
}
output = JsonConvert.SerializeObject(clanJson);
return output;
}
I'm using the same concept as found here: http://www.codeproject.com/Articles/45275/Create-a-JSON-WebService-in-ASP-NET-with-a-jQu
The Clan table has a circular reference to the Users table so that's why I am creating a temp object to serialize. My JSON data looks like this:
[
{
"Clan_Id": 1,
"Clan_Name": "Dog LB",
"Owner": null,
"DateRegistered": "0001-01-01T00:00:00"
},
{
"Clan_Id": 2,
"Clan_Name": "Frazzes",
"Owner": null,
"DateRegistered": "0001-01-01T00:00:00"
},
{
"Clan_Id": 3,
"Clan_Name": "Goobers",
"Owner": null,
"DateRegistered": "0001-01-01T00:00:00"
},
{
"Clan_Id": 4,
"Clan_Name": "DooGooers",
"Owner": null,
"DateRegistered": "0001-01-01T00:00:00"
}
]
And finally here is my AJAX call:
<script type="text/javascript" src='<%=Page.ResolveUrl("~/Scripts/jquery-2.1.1.min.js") %>'> </script>
<script>
window.onload = function () {
$.ajax({
type: "POST",
url: "http://localhost:8379/Services/CounterStrike.asmx/GetClans",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$.each(msg.d, function (index, elem) {
alert(index + ":" + elem);
});
},
error: function (xhr, ajaxOptions, thrownError)
{ alert(xhr.status); alert(thrownError); }
});
}
</script>
My HTML:
<p>
<b>Choose a Clan:</b>
<select id="clans">
<option value="-1">-- Select a Clan --</option>
</select>
</p>
<div id="users"></div>
On page load, i'm making an ajax call to the db to poll the list of clans which is serialized to json and populates the drop down list. Unfortunately, I do not get a popup of each clan. Instead, I check the javascript console and see:
Uncaught TypeError: Cannot use 'in' operator to search for '353' in
[{"Clan_Id":1,"Clan_Name":"Dog
LB","Owner":null,"DateRegistered":"0001-01-01T00:00:00"},{"Clan_Id":2,"Clan_Name":"Frazzes","Owner":null,"DateRegistered":"0001-01-01T00:00:00"},{"Clan_Id":3,"Clan_Name":"Goobers","Owner":null,"DateRegistered":"0001-01-01T00:00:00"},{"Clan_Id":4,"Clan_Name":"DooGooers","Owner":null,"DateRegistered":"0001-01-01T00:00:00"}]
Any ideas? Thanks!
Ah ha! Success. After two days of digging, I found that all i needed was to add an eval to my response data:
success: function (msg) {
$.each(eval(msg.d), function (index, elem) {
alert(index + ":" + elem);
});
},
and everything worked!

SELECT2 ajax - preloaded options

At the moment I have a dropdown that works with ajax request to the server, but it also be nice to attach some default options on select2 initialization. With initSelection function I only can attach one option, but not full preloaded array. I was also trying to use data option but it's doesn't work too.
Here is my code:
$("#address-select2").select2({
placeholder: "--- ' . t('I\'ll add new address') . ' ---",
minimumInputLength: 3,
ajax: {
url: "/ajax/address_autocomplete/from",
dataType: "json",
type: "POST",
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return {results: data.addresses};
}
},
initSelection: function (element, callback) {
$.ajax("/ajax/address_autocomplete/from/100", {
dataType: "json"
}).done(function(data) {
callback(data.addresses[0]);
});
},
formatResult: function (address) {
return "<span class=\"dropdown-element\">" + address.text + "</span>";
},
formatSelection: function (address) {
return address.text;
},
formatNoMatches: function () { return "' . t('No result found!') . '";},
formatSearching: function () { return "' . t('Searching...') . '"; },
formatLoadMore: function (pageNumber) { return "' . t('Loading results...') . '"; },
dropdownCssClass : "bigdrop"
});
please do not pass callback(data.addresses[0]);
please pass array directly like this callback(data.addresses);
it should work i have done it.

JSON, jQueryUI Autocomplete, AJAX - Cannot get data when array is not local

I have searched stackoverflow, as well as the web for some insight into how to get the jQueryUI Autocomplete plugin working with my JSON data, and I'm at a loss. I had it working like a charm with a local data array. I was able to pull values and build html.
I ran into a problem when I had to pull JSON form this source:
/Search/AjaxFindPeopleProperties2
?txtSearch=ca pulls up the test data that I am trying to loop through, when I type in 'ca' to populate the autocomplete list. One of the problems is that ?term=ca is appended to the url instead of ?txtSearch=ca and I'm not sure how to change it.
This is an example of the data:
{
"MatchedProperties": [
{
"Id": 201,
"Name": "Carlyle Center",
"Description": "Comfort, convenience and style are just a few of the features you'll ...",
"ImageUrl": "/Photos/n/225/4989/PU__ThumbnailRS.jpg"
}
]
}
...and here is the ajax call I'm trying to implement:
$(document).ready(function () {
val = $("#txtSearch").val();
$.ajax({
type: "POST",
url: "/Search/AjaxFindPeopleProperties2",
dataType: "json",
data: "{}",
contentType: "application/json; charset=utf-8",
success: function (data) {
$('#txtSearch').autocomplete({
minLength: 0,
source: data.d, //not sure what this is or if it's correct
focus: function (event, ui) {
$('#txtSearch').val(ui.item.MatchedProperties.Name);
$.widget("custom.catcomplete", $.ui.autocomplete, {
//customize menu item html here
_renderItem: function (ul, item) {
return $("<li class='suggested-search-item" + " " + currentCategory + "'></li>")
.data("item.autocomplete", item)
.append($("<a><img src='" + item.MatchedProperties.ImageUrl + "' /><span class='name'>" + item.MatchedProperties.Name + "</span><span class='location'>" + "item.location" + "</span><span class='description'>" + item.MatchedProperties.Description + "</span></a>"))
.appendTo(ul);
},
_renderMenu: function (ul, items) {
var self = this,
currentCategory = "Properties Static Test Category";
$.each(items, function (index, item) {
if (item.category != currentCategory) {
ul.append("<li class='suggested-search-category ui-autocomplete-category'>" + currentCategory + "</li>");
//currentCategory = item.category;
}
self._renderItem(ul, item);
});
}
}//END: widget
//return false;
},
select: function (event, ui) {
$('#txtSearch').val(ui.item.MatchedProperties.Name);
//$('#selectedValue').text("Selected value:" + ui.item.Abbreviation);
return false;
}
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
}); //END ajax
}); //END: doc ready
and I'm initializing here:
<script type="text/javascript">
//initialize autocomplete
$("#txtSearch").autocomplete({ //autocomplete with category support
/*basic settings*/
delay: 0,
source: "/Search/AjaxFindPeopleProperties2",
autoFocus: true,
minLength: 2 //can adjust this to determine how many characters need to be entered before autocomplete will kick in
});
//set auto fucus
$("#txtSearch").autocomplete("option", "autoFocus", true);
</script>
any help would be great...
Thanks!

Jquery UI Autocomplete Ajax JSONP return is broken in JQ UI Version 1.8.6

Ive been using the code below for my auto-completes on my form for a while , but after updating jquery ui to version 1.8.6 from 1.8rc3 it has broken the formatting of the JSONP return. The returned data is no longer formatted html, but instead it is a string. Any Ideas?
Update: JS Fiddle included, using the jquery ui demo and html in the data
http://jsfiddle.net/blowsie/ejLPg/
$("#companyname").autocomplete({
source: function (request, response) {
$.ajax({
url: turl,
dataType: "jsonp",
data: {
maxRows: 9,
name_startsWith: request.term
},
success: function (data) {
response($.map(data, function (item) {
return {
label: "<span class='ui-menu-item-title'>" + item.name.toLowerCase() + "</span><span class='ui-menu-item-subtitle'>" + item.address1.toLowerCase() + ' ' + item.post_code.toLowerCase() + '</span>',
value: item.name_id
}
}))
}
})
},
minLength: 3,
delay: 50,
select: function (event, ui) {
LoadGivenCompany(ui.item.value);
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
},
focus: function () { return false }
});
Thanks in advance
I looked into the source code of autocomplete of version 1.8.6 and found out that item creation uses text method instead of the html method. They suggest at jQuery.ui to change style using the theme roller of by altering the widget specific classes in the css file.
See Autocomplete#theming.
What i would do is find the place that they push the text in the element and change the method call back to html and test it out.
Turns out by using the .data(), after the autocomplete allows you to format the data
$(function() {
function log(message) {
$("<div/>").text(message).prependTo("#log");
$("#log").attr("scrollTop", 0);
}
$("#city").autocomplete({
source: function(request, response) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function(data) {
response($.map(data.geonames, function(item) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name,
test: 'hahahah'
}
}));
}
});
},
minLength: 2,
select: function(event, ui) {
log(ui.item ? "Selected: " + ui.item.label : "Nothing selected, input was " + this.value);
},
open: function() {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function() {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "<br>" + item.test + "</a>" )
.appendTo( ul );
};
});
http://jsfiddle.net/blowsie/ejLPg/3

Resources