我有2个自动完成jquery功能。我想在第二个中仅显示基于第一个文本字段中选择的值的值。我不想更改原始的aVal数组,因为如果有人更改了第一个txt值,则第二个必须对其进行调整。
以下是代码和JSFiddle:
$(function() {
var shared;
var aVal = [{label: "odd", value: "1"},
{ label: "even", value: "2"}
];
var bVal = [{ label: "one", value: "1"},
{ label: "two", value: "2"},
{ label: "three", value: "1"},
{ label: "four", value: "2"}
];
$( "#input_txt" ).autocomplete({
minLength: 0,
source: aVal,
focus: function( event, ui ) {
$( "#input_txt" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#input_txt" ).val( ui.item.label );
$( "#input_val" ).val( ui.item.value );
shared = ui.item.value;
return false;
}
})
$( "#second_input_txt" ).autocomplete({
minLength: 0,
source: bVal,
focus: function( event, ui ) {
if(ui.item.value == shared){
$( "#second_input_txt" ).val( ui.item.label );
}
return false;
},
select: function( event, ui ) {
$( "#second_input_txt" ).val( ui.item.label );
$( "#second_input_val" ).val( ui.item.value );
return false;
}
})
});
答案 0 :(得分:0)
这是正确的解决方案(源函数只有一点错误 - 感谢https://stackoverflow.com/users/1913845/ovaherenow)
$(function() {
var share=-1;
var aVal = [{
label: "odd",
value: "1"
},
{
label: "even",
value: "2"
}
];
var bVal = [{
label: "one",
value: "1"
},
{
label: "two",
value: "2"
},
{
label: "three",
value: "1"
},
{
label: "four",
value: "2"
}
];
$( "#input_txt" ).autocomplete({
minLength: 0,
source: aVal,
focus: function( event, ui ) {
$( "#input_txt" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#input_txt" ).val( ui.item.label );
$( "#input_val" ).val( ui.item.value );
share = ui.item.value;
//alert(share);
return false;
}
})
$( "#second_input_txt" ).autocomplete({
minLength: 0,
source: function(request, response){
var bValnew=new Array();
if(share==-1) return bValnew;
for(var a=0;a<bVal.length;a++){
if(bVal[a].value==share){
bValnew.push(bVal[a]);
}
}
response(bValnew);
},
focus: function( event, ui ) {
$( "#second_input_txt" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#second_input_txt" ).val( ui.item.label );
$( "#second_input_val" ).val( ui.item.value );
return false;
}
})
});