function generalSelectSort(selector_id,value,text) { var first = ''; if ($("#"+selector_id).children("option").length === 0) { $("#operation_selector").append('<option value="' + value + '">' + text + '</option>'); first = text; } var appended = 0; $("#"+selector_id).children("option").each(function(){ if($(this).text().toLowerCase() > text.toLowerCase() && appended === 0) { $(this).before('<option value="' + value + '">' + text + '</option>'); appended = 1; } }); // the last one if(appended === 0 && first !== text) { $("#"+selector_id).append('<option value="' + value + '">' + text + '</option>'); } }