小智..
5
选择的答案已经过时,熔化/ ajax选择的插件也是如此.
使用Select2插件有很多错误,我无法解决它.
这是我对这个问题的回答.
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 2000; //time in ms (2 seconds)
var selectID = 'YourSelectId'; //Hold select id
var selectData = []; // data for unique id array
//on keyup, start the countdown
$('#' + selectID + '_chosen .chosen-choices input').keyup(function(){
// Change No Result Match text to Searching.
$('#' + selectID + '_chosen .no-results').html('Searching = "'+ $('#' + selectID + '_chosen .chosen-choices input').val() + '"');
clearTimeout(typingTimer); //Refresh Timer on keyup
if ($('#' + selectID + '_chosen .chosen-choices input').val()) {
typingTimer = setTimeout(doneTyping, doneTypingInterval); //Set timer back if got value on input
}
});
//user is "finished typing," do something
function doneTyping () {
var inputData = $('#' + selectID + '_chosen .chosen-choices input').val(); //get input data
$.ajax({
url: "YourUrl",
data: {data: inputData},
type:'POST',
dataType: "json",
beforeSend: function(){
// Change No Result Match to Getting Data beforesend
$('#' + selectID + '_chosen .no-results').html('Getting Data = "'+$('#' + selectID + '_chosen .chosen-choices input').val()+'"');
},
success: function( data ) {
// iterate data before append
$.map( data, function( item ) {
// matching data eg: by id or something unique; if data match: not append - else: append
// This will prevent from select the same thing twice.
if($.inArray(item.attr_hash,selectData) == -1){
// if not match then append in select
$('#' + selectID ).append('' + item.data + '');
}
});
// Update chosen again after append
$('#' + selectID ).trigger("chosen:updated");
}
});
}
// Chosen event listen on input change eg: after select data / deselect this function will be trigger
$('#' + selectID ).on('change', function() {
// get select jquery object
var domArray = $('#' + selectID ).find('option:selected');
// empty array data
selectData = [];
for (var i = 0, length = domArray.length; i < length; i++ ){
// Push unique data to array (for matching purpose)
selectData.push( $(domArray[i]).data('id') );
}
// Replace select to only selected option
$('#' + selectID ).html(domArray);
// Update chosen again after replace selected
$('#' + selectID ).trigger("chosen:updated");
});