Reputation: 220877
I'm using a jquery widget similar to the example provided by jQuery UI for comboboxes:
http://jqueryui.com/demos/autocomplete/#combobox
This combobox decorates a select like this:
$('select[name=myselect]').combobox();
Now in some other piece of logic, I'd like to change the select, including all of its contents:
$('select[name=myselect]').empty();
$('select[name=myselect]').append(
$('select[name=otherselect]').children().clone());
$('select[name=myselect]').val('new-value');
Now how can I get the combobox to re-render?
Upvotes: 0
Views: 155
Reputation: 220877
I found a solution to my problem by extending the aforementioned combobox control. XGreen's first suggestion using
$('.selector').live("change", ...)
didn't work because the change event is not triggered when modifying a select using .val()
(at least not in jquery 1.4.4. Upgrading is not possible right now)
Hence, I added this code to the combobox's construction:
select.observe_field(1, function() {
var selected = select.children(":selected");
var value = selected.val() ? selected.text() : "";
input.val(value);
});
Where observe_field
is some not soo efficient function found on the web:
jQuery.fn.observe_field = function(frequency, callback) {
return this.each(function(){
var element = $(this);
var prev = element.val();
var chk = function() {
var val = element.val();
if(prev != val){
prev = val;
element.map(callback); // invokes the callback on the element
}
};
chk();
frequency = frequency * 1000; // translate to milliseconds
var ti = setInterval(chk, frequency);
// reset counter after user interaction
element.bind('keyup', function() {
ti && clearInterval(ti);
ti = setInterval(chk, frequency);
});
});
};
Better solutions are still very welcome!
Upvotes: 1
Reputation: 11558
Sorry I just checked and the widget seem to have its own change event:
click view source here to see the complete example
change: function( event, ui ) {
if ( !ui.item ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
valid = false;
select.children( "option" ).each(function() {
if ( $( this ).text().match( matcher ) ) {
this.selected = valid = true;
return false;
}
});
if ( !valid ) {
// remove invalid value, as it didn't match anything
$( this ).val( "" );
select.val( "" );
input.data( "autocomplete" ).term = "";
return false;
}
}
}
Upvotes: 1