ajax-chosen
ajax-chosen copied to clipboard
Programmatically force to search
Hey, what about a challenge? :)
What I need to do is to have an option to trigger a search from my program code - followed by selecting an item from the list.
Example:
The list contains the items
-
- peach
-
- pineapple
-
- passiflora
The user clicks on a button somewhere in the page. That button should trigger an event and force the list to be set to "apple"
ajaxChosen would need to do an ajax request to fetch the id and the item "apple", modify the list and then select the specified item.
I will try to solve that myself now, but I'll do it in JavaScript. No time to learn CoffeeScript now.
For everybody interested: here is my jQuery code to force the list to include a given item. It's based on my special case where #chzn is the chosen box:
var setBox = function(id) {
var $opt = $('#chzn option[value="' + id+ '"]');
if ($opt.length == 0) {
// Need to load first
$.ajax({
'url': 'ajax.asp',
'data': {"id": id},
success: function(data, t, x) {
if (data.length == 1) {
var $opt = $('<option value="' + data[0]['id'] + '">').html(data[0]['text']);
$('#chzn').append($opt).val(data[0]['id']).trigger("liszt:updated");
} else {
// Deal with "not found" state.
}
}
});
} else {
// Already exists
$('#chzn').val(id).trigger("liszt:updated");
}
}
This code exists outside the ajax-chosen environment but might be worth to add.