Last active
April 14, 2021 23:55
-
-
Save wplokal/68a6c79e0c4298d7d7deb965eb6504ea to your computer and use it in GitHub Desktop.
select2 ajax chained - wilayah indonesia
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
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