我有一个功能,当用户输入城市的邮政编码时,城市名称将设置为城市名称输入字段。搜索工作正常但我无法获得输入字段的相对ID并在那里设置名称。我无法对其ID进行硬编码,因为这些表单是动态生成的。
$("[id*=post_code]").on("input", function() {
var el = $(this);
if (el.val().length > 2) {
$.ajax({
url: url,
cache: false,
dataType: "json",
type: "GET",
data: "post-code=" + el.val(),
success: function(result, success, e) {
//DOES NOT WORK
$(e.target).parents(".city-auto").find("[id*=city]").val(result.name);
}
});
}
});
<div class="row 50% city-auto">
<div class="3u 12u(narrower)">
<div class="form-warning">
{% if client_form.post_code.errors %}
<spam><img src="{{ STATIC_URL }}icons/warning_triangle_16.png" class="icon"> <spam class="icon fa-angle-down"></spam></spam>
{% endif %}
</div>
<!-- Triggers JavaScript -->
<input id="id_form-0-post_code" maxlength="5" name="form-0-post_code" placeholder="Post nr." type="text">
</div>
<div class="6u 12u(narrower)">
<div class="form-warning">
</div>
<!-- Should get value replaced by JavaScript -->
<input id="id_form-0-city" maxlength="30" name="form-0-city" placeholder="By" type="text" readonly="">
</div>
</div>
此表单是动态生成的,因此我需要能够通过指定正则表达式或使用通配符来查找城市输入ID,就像我一样。
答案 0 :(得分:2)
el.parent().next().find("[id*=city]").val(result.name);
解释
el.parent()
:
<div class="3u 12u(narrower)">
.next()
:
<div class="6u 12u(narrower)">
.find("[id*=city]")
:
<input id="id_form-0-city" maxlength="30" name="form-0-city" placeholder="By" type="text" readonly="">