jQuery只需要根据其他字段的值自动填充一个输入字段(行)(自动完成);所有其他字段必须保持不变

jQuery need automatically fill only one input field (row) based on value in other field (autocomplete); all other fields must remain unchanged

本文关键字:字段 其他 一个 jQuery 填充 输入      更新时间:2023-09-26

这个http://af-design.com/blog/2010/05/12/using-jquery-uis-autocomplete-to-populate-a-form/脚本根据城市自动填充州和zip。

有一行id为id="city"。如果我想要额外的行,我必须使用id="city1", id="city2"等。

在javascript代码中,可以使用

$("#city").val(ui.item.city);

$("#city1").val(ui.item.city1);

如果我有很多行,这是不行的。

所以我试着改变。下面是修改后的代码

$(document).ready(function(){
var ac_config = {
source: "__demo_cities.php",
select: function(event, ui){
$('[id^="city"]').val(ui.item.city);
$('[id^="state"]').val(ui.item.state);
$('[id^="zip"]').val(ui.item.zip);
},
minLength:1
};
$('[id^="city"]').autocomplete(ac_config);
});
HTML

<input type="text" name="city[]" id="city" value="" />
<input type="text" name="state[]" id="state" value="" />
<input type="text" name="zip[]" id="zip" value="" />
<br>
<input type="text" name="city[]" id="city1" value="" />
<input type="text" name="state[]" id="state1" value="" />
<input type="text" name="zip[]" id="zip1" value="" />

如果我在city脚本中输入一些东西,它会自动填充id="state", id="zip"(这是可以的),但它也会自动填充id="city1", id="state1"id="zip1"(这是不必要的)。

需求行为:如果在id="city"中输入内容,则自动只填充id="state"id="zip",其他字段保持空白/不变;如果输入id="city1",则自动只填写id="state"id="zip",其他字段保持空白/不变。

基于@JNF建议,有一段代码可以工作

$(document).ready(function(){
var ac_config = {
source: "__demo_cities.php",
select: function(event, ui){
$(this).closest(".myForm").find('[id^="city"]').val(ui.item.city);
$(this).closest(".myForm").find('[id^="state"]').val(ui.item.state);
$(this).closest(".myForm").find('[id^="zip"]').val(ui.item.zip);
},
minLength:1
};
$('[id^="city"]').autocomplete(ac_config);
});

你使用的[id^="city"]选择器意味着"任何以city开头的东西",所以它也会影响city1。其他的也一样。

我会把它们放在另一个元素中,像这样:

<span class="myForm">
  <input type="text" name="city[]" id="city" value="" />
  <input type="text" name="state[]" id="state" value="" />
  <input type="text" name="zip[]" id="zip" value="" />
</span>
<span class="myForm">
  <br>
  <input type="text" name="city[]" id="city1" value="" />
  <input type="text" name="state[]" id="state1" value="" />
  <input type="text" name="zip[]" id="zip1" value="" />
</span>

然后在jQuery中输入

$(this).closest(".myForm").find("[id^=state]") etc...

我会将类分配给您的输入,按类选择它们更快,然后按其id中的子字符串:

HTML

<input type="text" class="city" name="city[]" id="city0" value="" />
<input type="text" class="state" name="state[]" id="state0" value="" />
<input type="text" class="zip" name="zip[]" id="zip0" value="" />
<br>
<input type="text" class="city" name="city[]" id="city1" value="" />
<input type="text" class="state" name="state[]" id="state1" value="" />
<input type="text" class="zip" name="zip[]" id="zip1" value="" />
JavaScript

$( ".city" ).change(function(e) {
var anIDString=this.id;
anIDString = anIDString.replace('city','zip');
$('#'+anIDString).val('This one changed!');
}
);