Reputation: 2510
In my project I'm using three chained selects.
html
<select name="id_foo">
<option value="1">one</option>
<option value="2">two</option>
</select>
<select name="id_bar">
</select>
<select name="id_doe">
</select>
<br>
<input type="button" id="auto" value"auto complete">
js
var $sel_foo = $('select[name="id_foo"]');
var $sel_bar = $('select[name="id_bar"]');
var $sel_doe = $('select[name="id_doe"]');
/** Chained Select (id_foo) */
$sel_foo.on('change', function() {
var id_foo = this.value;
$.ajax({
type : "POST",
url : ajax.php,
data : { id_foo: id_foo },
success : function(data) {
$sel_bar.html(data);
}
});
});
/** Chained Select (id_bar) */
$sel_bar.on('change', function() {
var id_bar = this.value;
$.ajax({
type : "POST",
url : ajax.php,
data : { id_bar: id_bar },
success : function(data) {
$sel_doe.html(data);
}
});
});
For simulte the human action I use the trigger method. Unfortunately I had to enter a timeout (2 sec) between triggers methods otherwise select were called before they were loaded entirely (ajax response)
$('#auto').on('click', function(){
$sel_foo.trigger("change");
setTimeout( function() { $sel_bar.trigger("change"); }, 2000);
});
I would try to do it cleaner, running the next trigger only when the called function from the previous trigger is finished. How could I do this? thank you
EDIT
I tried this, but with no success.
$.when($sel_foo.trigger("change"))
.then($sel_bar.trigger("change"));
Upvotes: 0
Views: 206
Reputation: 74420
You could use the following logic:
$sel_foo.on('change', function(e) {
var id_foo = this.value,
self = this; // keep ref on `this`
$.ajax({
type : "POST",
url : "/echo/html",
data : { id_foo: id_foo },
success : function(data) {
$sel_bar.html(data);
if(e.isTrigger) $sel_bar.trigger('change');
}
});
});
$('#auto').on('click', function(){
$sel_foo.trigger("change"); // on click only trigger first SELECT change event
});
Upvotes: 1