Gam*_*mer 5 javascript jquery select typeahead.js
我有一个选择框(Specie)和一个typeAhead输入字段(Breed),我需要更新selectbox的更新,我有以下代码.
<div class="col-lg-4 col-md-4 col-sm-12 col-xs-12 profile-fields-margin-bottom">
<select class="form-control select_field_style specie-breed" id="species" name="species" required>
<option disabled selected>Select a Species</option>
<option value="Dog">Dog</option>
<option value="Cat">Cat</option>
<option value="Horse">Horse</option>
</select>
</div>
<div class="col-lg-4 col-md-4 col-sm-12 col-xs-12 profile-fields-margin-bottom">
<input id="breed" type="text" class="form-control charsonly" name="breed" placeholder="Breed">
</div>
$(document).on('change', '.specie-breed', function() {
let specie = this.value;
$('#breed').typeahead({
source: function (query, process) {
return $.get('/get/breeds/' + specie, { query: query }, function (data) {
console.log(data);
return process(data);
});
}
});
});
Run Code Online (Sandbox Code Playgroud)
它的工作但是第一次,第二次更改不会改变typeahead的值,
我在这里失踪了什么?
它的工作但是第一次,第二次更改不会改变typeahead的值,
我认为这是因为第二,第三等时间,AJAX URL不再被改变; 这是因为specie遗骸是最初分配给它的值.
我的意思是,让我们说你Cat从下拉菜单中选择了; 所以该change菜单的第一个事件被触发,并被specie设置为Cat.但是,当您稍后选择Horse(或Dog)时,选项specie 的闭包内的fromsource仍为Cat.
此笔可能会帮助您理解它.
因此,一个简单的解决将是引用specie到this,而不是this.value.
$(document).on('change', '.specie-breed2', function() {
let specie = this; // Reference the Element.
$('#breed').typeahead({
source: function (query, process) {
return $.get('/get/breeds/' + specie.value, { query: query }, function (data) {
console.log(data);
return process(data);
});
}
});
});
Run Code Online (Sandbox Code Playgroud)
或者你可以这样做:
$('#breed').typeahead({
source: function (query, process) {
if ( ! $( '#species' ).val() ) {
return;
}
return $.get('/get/breeds/' + $( '#species' ).val(), { query: query }, function (data) {
console.log(data);
return process(data);
});
}
});
Run Code Online (Sandbox Code Playgroud)
UPDATE
实际的解决方案,或者你在代码中遗漏的内容(我认为)是:在重新初始化该字段之前销毁该字段typeahead#breedtypeahead.
$(document).on('change', '.specie-breed', function() {
let specie = this.value;
// Destroy existing instance.
$('#breed').typeahead( 'destroy' );
// (Re-)Initialize `typeahead`.
$('#breed').typeahead({
source: function (query, process) {
return $.get('/get/breeds/' + specie, { query: query }, function (data) {
console.log(data);
return process(data);
});
}
});
});
Run Code Online (Sandbox Code Playgroud)
这样,specie可以分配或引用this.value(即当前选择的"物种"),并且您将获得正确的值(例如Cat或Dog).
请参阅jQuery #typeahead('destroy').
| 归档时间: |
|
| 查看次数: |
655 次 |
| 最近记录: |