jQuery自动完成多个字段使用id,但不使用类;如果可能的话,使用序列化

jQuery autocomplete for multiple fields using id, but not using class; using serialize if possible

本文关键字:如果 序列化 id jQuery 字段      更新时间:2023-09-26

HTML输入字段

<input type="text" name="partner_name_or_description[]" id="partner_name_or_description1" class="row_changed1"/>
<input type="text" name="partner_name_or_description[]" id="partner_name_or_description2" class="row_changed2"/>
<input type="text" name="partner_name_or_description[]" id="partner_name_or_description3" class="row_changed3"/>

部分jquery自动完成代码(可以工作)

$("#partner_name_or_description1:input, #partner_name_or_description2:input, #partner_name_or_description3:input").autocomplete(
"__autocomplete_source.php",

在jquery有:partner_name_or_description1, 2, 3等....我想在serialize(或其他可能的方式)中使用一些简短的内容来代替这个包含1、2、3等的长列表。

首先得到这些1,2,3…使用下面的代码

$('[id^="partner_name_or_description"]').each(function (index, partner_name_or_description) {
var s_id = partner_name_or_description.id.substring(27);
});

那就不要再写那么长的列表了

$("#partner_name_or_description" + s_id + " :input").serialize().autocomplete(

它不工作。如果查看源代码,请参见

 $("#partner_name_or_description" + s_id + " :input").serialize().autocomplete(

不明白原因…可能不正确使用serialize().autocomplete

或者可以不使用serialize(),而必须使用其他东西。

我不能使用class="row_changedX",因为它是必要的其他目的(类必须像row_changed1,2,3;对于每一行,类名必须不同)。

/*Actually do not understand why this is necessary, but if I delete all uncommented, then code does not work*/
function findValue(li) {
/*if( li == null ) return alert("No match!");
// if coming from an AJAX call, let's use the CityId as the value
if( !!li.extra ) var sValue = li.extra[0];
// otherwise, let's just display the value in the text box
else var sValue = li.selectValue;
alert("The value you selected was: " + sValue);*/
}
function selectItem(li) {
findValue(li);
}
function formatItem(row) {
return row[0] + " (id: " + row[1] + ")";
}
$('[id^="partner_name_or_description"]').autocomplete("__autocomplete_source.php",
{
delay:10,
minChars:2,
matchSubset:1,
matchContains:1,
cacheLength:10,
onItemSelect:selectItem,
onFindValue:findValue,
formatItem:formatItem,
autoFill:true
}//{ delay:10,
)//.autocomplete(;

编辑:感谢@jk -这将工作:

$('[id^="partner_name_or_description"]').autocomplete(
        "__autocomplete_source.php",
        //do stuff
});