0

I have been trying to fill multiple input fields using jquery autocomplete in my Django app.

As an example, my model is somewhat like this:

class Country(models.Model):
    country_code = models.CharField(max_length=2,  ...) # To store ISO codes
    name = models.CharField(max_length=60,...) # To store country name

Now using the following script to call ajax function on an html template:

$(function() {
    $( "#id_country" ).autocomplete({
        source: "{% url ... %}",
        select: function(e, ui) {
            $("#id_country").val(ui.item.id);
        //  $("#id_country_code_txt").val(ui.item.label);   // I need to populate this input field
            $("#id_country_txt").val(ui.item.label);
            return false;
        },
        ...
        ...
    });
});

and the following function in my views.py:

def CountrySearch(request):
    if request.is_ajax():
        q = request.GET.get('term','')
        names = Country.objects.filter(name__icontains=q).annotate(value=F('name'), label=F('name')).values('id', 'value', 'label')
        result = list(names)
        data = json.dumps(result)
    mimetype = 'application/json'
    return HttpResponse(data, mimetype)

I am able to fill (autocomplete) one of the input fields (refer the image with fields id and country_name populated). What I am aiming to do, however, is to fill the other dependent value of id (of the Country model) as well into input field id_country_code_txt (the field marked with an arrow).

In order to get the value of model field "country_code" (i.e the ISO Code), I added an additional query as below and modified the function to:

def CountrySearch(request):
    ...
        ...
        names = Country.objects.filter(name__icontains=q).annotate(value=F('name'), label=F('name')).values('id', 'value', 'label')
        country_codes = Country.objects.filter(country_code__icontains=q).annotate(value=F('country_code'), label=F('country_code')).values('id', 'value', 'label')
        result = list(names) + list(country_codes)
        print('HERE ARE THE results COLLECTED: ' + str(result)) # To see the values being picked up
        ...
        ...

In the terminal as I print out the values of the generated list (containing both the fields namely country_code and country_name), the resultant list is as follows:

[
{'id': 2, 'value': 'United States of America', 'label': 'United States of America'}, 
{'id': 2, 'value': 'US', 'label': 'US'}
]

What I am struggling to do is to pass the value US to the input field id_country_code_txt marked in the image with an arrow.

Shall appreciate if someone can show me a way how to achive this.

Edit: An image of the fields in the question (part of the form) added. Please have a look. enter image description here

9
  • Do not see anything that looks out of place. Please provide a Minimal, Reproducible Example: stackoverflow.com/help/minimal-reproducible-example Commented Mar 30, 2022 at 22:59
  • Thanks for your reply. Added and image and further clarifications. Please have a look. Commented Mar 31, 2022 at 4:15
  • Can you show your html structure Commented Mar 31, 2022 at 4:38
  • The function() in my question above is part of the html template, which is very basic. Like I have said, I am able to autocomplete search on one of the fields, only that I am looking for ways to pick up all related fields' values and populate the relevant fields in the form. For example, the case would be similar to picking up all relevant product information when the user keys in the product_code or product_name (as happens in a POS or a similar system) and selects one of the results and the underlying values get picked up. I hope it is clear now. Commented Mar 31, 2022 at 5:15
  • @user12379095 you will need a complex source function that can can identify the field that is being used to initiate the search and then perform a search based on that details.The results can go into all the fields, yet each search will have a unique search term, I. E., a code is different than a name. Commented Mar 31, 2022 at 17:10

1 Answer 1

0

Consider the following. This is a non-tested example.

$(function() {
  $(".country input").autocomplete({
    source: function(request, response) {
      // Define default URL base
      var url = "views.py?term=" + request.term;
      var $self = $(".country input:focus");
      // Define the search to use: ID, Code, Name
      switch ($self.attr("id")) {
        case "id_country":
          url += "&queryType=id";
          break;
        case "id_country_code_txt":
          url += "&queryType=code";
          break;
        case "id_country_txt":
          url += "&queryType=name";
          break;
      }
      console.log(url);
      // Perform GET requestfor JSON data
      $.getJSON(url, function(data) {
        // Send Data to Autocomplete
        response(data);
      });
    },
    select: function(e, ui) {
      $("#id_country").val(ui.item.id);
      $("#id_country_code_txt").val(ui.item.value);
      $("#id_country_txt").val(ui.item.label);
      return false;
    }
  });
});
.sm {
  width: 4em;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.js"></script>
<div class="country">
  <label>Country:</label>
  <input id="id_country" class="sm" type="text" />
  <input id="id_country_code_txt" class="sm" type="text" />
  <input id="id_country_txt" type="text" />
</div>

Regardless of the Users entry into the fields, Autocomplete will seek results from Python. If there is a unique search page for each type of search, you can assign it in the switch along with the other parts of the query.

Each lookup should return the same structure: [{ id, label, value }]

When the User selects on of the options, all fields will be populated.

See More:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.