Reputation: 317
I'm trying to make an autocomplete for multiple inputs.
this is the suggestions:
<div id="person" class="204232">
<div class="name" >John Smiths</div>
<div class="age" >25 years</div>
</div>
<div id="person" class="204255">
<div class="name" >Michael Sosh</div>
<div class="age" >31 years</div>
</div>
I need to make something, when I click at div #person, autocomplete this form.
<form ...>
<input type="text" name="name" />
<input type="text" name="age" />
<input type="text" name="adress" />
<input type="text" name="city" />
<input type="text" name="country" />
</form>
I can get these informations JSON encoded on get.php?code=[.className of #person]
This is what i did, but it's not working.
$("#search").on(click, function() {
source: function (request, response) {
$.ajax({
url: "get.php?code="+$(this).attr('class'),
type: "GET",
data: request,
success: function (data) {
response($.map(data, function (el) {
return {
name: el.name
};
}));
}
});
},
select: function (event, ui) {
this.name = ui.item.name;
$('#name').val(ui.item.name);
event.preventDefault();
}
});
NOTE: In this example, I'm trying to autocomplete just the first input but i need to complete all.
Get.php?code=204232 return:
{"age":"25 years",
"name":"John Smiths",
"adress":"KariStr. 112",
"city":"London",
"country":"England"}
Upvotes: 0
Views: 773
Reputation: 16150
If you just want to set the inputs, you don't need to use source/select. Just call the ajax request, set the response type to JSON, and on the callback set the values directly like this:
$("#search").click(function() {
$.ajax({
url: "get.php?code="+$(this).attr('class'),
type: "GET",
dataType: 'json',
success: function (data) {
$("input[name='name']").val(data.name);
$("input[name='age']").val(data.age);
$("input[name='address']").val(data.address);
$("input[name='city']").val(data.city);
$("input[name='country']").val(data.country);
}
});
});
See that you were using the selector #name
that means id=name. You either add the id to the input tag or use the name selector as i did above.
Upvotes: 2