2

I'm trying to get the selected value of a typeahead input and I get this error every time: Uncaught TypeError: Cannot assign to read only property 'highlight' of. It never tells me what object it's referring to and it originates from within the TypeAhead.min.js file, so I can't say exactly what line of my code is causing it. Here's the code I use to set up and capture the value of the input:

$(".articles.new").ready ->
  engine = new Bloodhound {
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  local: autocomplete_items
}

engine.initialize()

$('#auto_complete').typeahead { hint: true, highlight: true, minLength: 1 },  
  { name: "names", displayKey: "name", source: engine.ttAdapter()}

$('#auto_complete').on 'typeahead:selected', (event, selection) ->
  alert selection.name
  $('#auto_complete').typeahead 'setQuery', ''
  event.stopPropagation()
  return
return

For context: auto_complete items is an array of objects from my controller with name property. I'm working in Ruby on Rails 4.1.4.

What can I do to fix this error? What is causing it?

1 Answer 1

11

I figured this out after much experimenting. The error was coming from this line $('#auto_complete').typeahead 'setQuery', ''. I was trying to clear the value from the input box after taking some other action with it. I'm not too sure of the technical details, but using $('#auto_complete').typeahead 'val', '' instead achieved the desired effect without the error. I suppose that explains why the object was blank, it was referring to an empty query and trying to take actions with it.

If anybody can give me a more detailed explanation of the difference between the two API calls I'd be interested to hear it out of curiosity, but if not I'm just happy to move on.

1
  • It appears to be related to the fact the val function is defined in the methods array and already initialised, but the setQuery is not. The initialise of the setQuery throws the error. So just looks like using val is the correct way to do it.
    – Peter Kerr
    Commented Nov 16, 2016 at 10:14

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.