LBJ33
LBJ33

Reputation: 449

Django - JQuery autocomplete custom select from multiple fields

I have a user search that autocompletes by both ticker and name. The search results come back as "{{ticker}} - {{name}}". When a result is selected, I want it to fill with only the ticker, where as it currently fills with "{{ticker}} - {{name}}".

Here is my python code:

if 'term' in request.GET:
    tickers = Company.objects.filter(ticker__istartswith = request.GET.get('term')) | Company.objects.filter(name__istartswith = request.GET.get('term'))
    companies = []
    for ticker in tickers:
        companyTicker = ticker.ticker +  " - " + ticker.name
        companies.append(companyTicker)
    return JsonResponse(companies, safe=False)

and here is my javascript:

    <script>
    $( function() {
      $( "#ticker3" ).autocomplete({
        source: '{% url "financials:get_financials" %}',
        select: function (event, ui) {
            ticker.ticker
        }
      });
    } );
    </script>

Any help greatly appreciated!

Upvotes: 1

Views: 537

Answers (1)

Rob Vezina
Rob Vezina

Reputation: 638

A quick look at the jquery autocomplete docs reveals that you can use an array of objects for your source option. Each object should have a label and value attribute. The following should get you what you need.

if 'term' in request.GET:
    tickers = Company.objects.filter(ticker__istartswith = request.GET.get('term')) | Company.objects.filter(name__istartswith = request.GET.get('term'))
    companies = []
    for ticker in tickers:
        label = f"{ticker.ticker} - {ticker.name}"
        companyTicker = {'label': label, 'value': ticker.ticker}
        companies.append(companyTicker)
    return JsonResponse(companies, safe=False)

You can then remove the select option in your javascript:

  <script>
      $(function () {
          $("#ticker3").autocomplete({
              source: '{% url "financials:get_financials" %}',
          });
      });
  </script>

Upvotes: 1

Related Questions