Reputation: 1966
I have the following json array:
partTags = [{"part":"Part1","dwg":"A"},{"part":"Part2","dwg":"B"}]
Which basically carries the Part Number and a corresponding Drawing Number/Letter
Prior to adding a second parameter ( "Drawing Number ") I just had the part number and I used jQuery autocomplete to search the array. What I want to do now is to Search for the part number in my first input: <input type="text" id="part_number">
and automatically add its corresponding Drawing Number to a second input: <input type="text" id="drawing_number">
upon clicking the part number.
Here is what I had:
$( "#part_number" ).autocomplete({
delay: 100,
source: partTags
});
How can I modify the code above to achieve this? I don't work much with jQuery so I'm quite lost when it comes to some of the API.
Here's what I have so far after fiddling a bit...
$( "#part_number" ).autocomplete({
delay: 45,
source: partTags,
select: function(event, ui)
{
$(this).val(ui.item.part);
$("input#drawing_number").val(ui.item.dwg);
return false;
}
});
Upvotes: 3
Views: 14128
Reputation: 359
I never used local string for autocomplete but the following worked.
$("#part_number").autocomplete({
minLength: 0,
source: function (request, response) {
$.post("/echo/json/", {
json: '[{"part":"Part1","dwg":"A"},{"part":"Part2","dwg":"B"}]',
delay: 1
}, function (data) {
response($.map(data, function (pn) {
return {
value: pn.dwg,
label: pn.part
};
}));
});
},
select: function (event, ui) {
$('#part_number').val(ui.item.label);
$("input#drawing_number").val(ui.item.value);
return false;
}
});
Here is a working demo
Upvotes: 1
Reputation: 1966
Well I figured it out after looking at the API.
partTags = [{"label":"Part1","dwg":"A"},{"label":"Part2","dwg":"B"}]
I had to re-name "part" to "label"
$( "#part_number" ).autocomplete({
delay: 45,
source: partTags,
select: function(event, ui)
{
$(this).val(ui.item.label);
$(this).closest('tr').find("input[id^='drawing_number']").val(ui.item.dwg);
return false; // find the drawing number input on that row
}
}).data( "autocomplete" )._renderItem = function(ul, item){
if(item.dwg!=null || item.dwg!='') // if the drawing is null or empty
{
return $( "<li></li>" ).data( "item.autocomplete", item ).append( "<a><strong>" + item.label + "</strong> - Rev " + item.dwg + "</a>" ).appendTo( ul );
}
else
{
return $( "<li></li>" ).data( "item.autocomplete", item ).append( "<a><strong>" + item.label + "</strong></a>" ).appendTo( ul );
}
};
Upvotes: 1