Skip to content

Instantly share code, notes, and snippets.

@wplokal
Last active April 14, 2021 23:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wplokal/68a6c79e0c4298d7d7deb965eb6504ea to your computer and use it in GitHub Desktop.
Save wplokal/68a6c79e0c4298d7d7deb965eb6504ea to your computer and use it in GitHub Desktop.
select2 ajax chained - wilayah indonesia
function ajaxChained(source,target,slug){
$(source).on('change',function(){
var pid = $(source+' option:selected').val(); //$(this).val();
$.ajax({
type: 'POST',
url: '{{ site_url() }}psb/'+slug+'/'+pid,
dataType: 'html',
data: { id : pid },
success: function(txt){
//no action on success, its done in the next part
}
}).done(function(data){
//get JSON
data = $.parseJSON(data);
//generate <options from JSON
var list_html = '';
$.each(data, function(i, item) {
list_html += '<option value='+data[i].id+'>'+data[i].name+'</option>';
});
//replace <select2 with new options
$(target).html(list_html);
//change placeholder text
$(target).select2({placeholder: data.length +' results'});
});
})
}
ajaxChained('#wilprov','#wilkab','regency');
ajaxChained('#wilkab','#wilkec','district');
ajaxChained('#wilkec','#wildes','village');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment