Reputation: 1567
I have a function that when the user types the city's post code, the name of the city is set to the city name input field. The search works fine but I can't get the relative id to the input field and set the name there. I can't hard code its ID because these forms are dynamically generated.
$("[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>
This form is dynamically generated, so I need to be able to find the city input id by specifying a regular expression or using wildcard, like I did.
Upvotes: 0
Views: 195
Reputation: 1
el.parent().next().find("[id*=city]").val(result.name);
Explanation
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="">
Upvotes: 2