Created
July 21, 2012 07:55
-
-
Save heaven/3155031 to your computer and use it in GitHub Desktop.
Ajax support for chosen
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
new function($) { | |
return $.fn.ajaxChosen = function(options, callback) { | |
var select = this, | |
chosen; | |
select.chosen(); | |
chosen = select.data('chosen'); | |
var val, | |
timeout = null, | |
delay = options.searchDelay || 500, | |
success = options.success || null, | |
input = select.next('.chzn-container').find(".search-field > input").length ? | |
select.next('.chzn-container').find(".search-field > input") : | |
select.next('.chzn-container').find(".chzn-search > input"); | |
options.beforeSend = function(xhr) { | |
xhr.setRequestHeader("Accept", "application/json"); | |
}; | |
options.success = function(data) { | |
if (data === null) return; | |
var selected_items = []; | |
select.find("option").each(function() { | |
if (!$(this).is(":selected")) { | |
return $(this).remove(); | |
} else { | |
selected_items.push({ id: this.value, label: this.text}); | |
} | |
}); | |
var items; | |
if (typeof callback == "function") { | |
items = callback(data); | |
} else { | |
items = data; | |
} | |
$(items).each(function() { | |
var item = this; | |
if (!$(selected_items).filter(function() { return this.id == item.id }).length) { | |
$("<option />").attr('value', item.id).html(item.label).appendTo(select); | |
} | |
}); | |
select.trigger("liszt:updated"); | |
input.attr('value', val); | |
input.css({ width: "auto" }); | |
if (typeof success == "function") return success(); | |
}; | |
input.bind("focus", function() { | |
if (!select.find("option").filter(function() { return !$(this).is(":selected") }).length) { | |
select. | |
next('.chzn-container'). | |
find('.chzn-results'). | |
html('<li class="no-results">Start Typing</li>'); | |
} | |
}); | |
input.bind("keyup", function() { | |
val = $.trim($(this).attr('value')); | |
if (val === $(this).data('prevVal')) return false; | |
if (timeout) clearTimeout(timeout); | |
select. | |
next('.chzn-container'). | |
find('.no-results'). | |
text(val.length < 2 ? "Keep typing..." : "Looking for \"" + val + "\""); | |
if (val.length < 2) return; | |
$(this).data('prevVal', val); | |
timeout = setTimeout(function() { | |
options.data = { query: val }; | |
$.ajax(options); | |
}, delay); | |
}); | |
}; | |
} (jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment