1

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!

3
  • You could return companyTicker as a dict in your json response. That way you could easily reference ticker and name independent of one another. companyTicker = {'ticker': ticker.ticker, 'name': ticker.name} Commented Jul 17, 2021 at 13:48
  • Are you able to give a full example as an answer? I tried that but still can't figure out how to use that as the selector. Commented Jul 17, 2021 at 14:26
  • I'm sorry. My above comment doesn't work with the jquery autocomplete function. I'll answer below. Commented Jul 17, 2021 at 14:48

1 Answer 1

1

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>
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.