I'm trying to use another functions at "complete:" JQuery ajax, after "selectOptionSort" function but doesn't work. What's wrong ?
$('#tipos').change(function(){
$("#marcas > option").remove();
$("#marcas").prepend('<option>-- Selecione a Marca --</option>');
$("#marcas").prepend('<option>-- Adicionar --</option>');
$("#modelos > option").html("<option selected=\"selected\" value=\"#\">-- Selecione o Modelo --</option>");
var tipo = $('#tipos').val();
$.ajax({
type: "POST",
url: BASE+"admin/getMarcas/"+tipo,
success: function(marcas)
{
$.each(marcas,function(id,marca)
{
var opt = $('<option />');
opt.val(id);
opt.text(marca);
$('#marcas').append(opt);
});
},
complete: function(){
$("#marcas").selectOptionSort({ //This works fine !
orderBy: "text",
sort: "asc"
});
//These two below doesn't work !
$("#marcas").append('<option>-- Teste Adicionar --</option>');
console.log("test");
}
});
});
Note: I've downloaded selectOptionSort from https://github.com/yadhi/jquery-select-option-sort
initialize selectOptionSort after you append another option to select box at your complete function:
$("#marcas").selectOptionSort(
{ //This works fine !
orderBy: "text",
sort: "asc"
});
$("#marcas").append('<option>-- Teste Adicionar --</option>');
$("#marcas").selectOptionSort(//reinitialize the selectOptionSort after appending
{ //This works fine !
orderBy: "text",
sort: "asc"
});
console.log("test");
look here under TEXT DESC for live example
Perhaps this works for you as this kind of syntax is what I often use:
$("#marcas").append('<option>-- Teste Adicionar --</option>');
to this:
$('<option>-- Teste Adicionar --</option>').appendTo("#marcas");
WHy don't you just do all the manipulation within one callback?
$.ajax({
type: "POST",
url: BASE + "admin/getMarcas/" + tipo,
success: function (marcas) {
$.each(marcas, function (id, marca) {
var opt = $('<option />');
opt.val(id);
opt.text(marca);
$('#marcas').append(opt);
});
/* is known all options are there, can sort now*/
$("#marcas").selectOptionSort({
orderBy: "text",
sort: "asc"
});
/* why append after sort?*/
$("#marcas").append('<option>-- Teste Adicionar --</option>');
console.log("test");
}
});
You must reinitialize the selectOptionSort
after each time you append.