Algolia Places And Rails: Autocomplete Form
Solution 1:
It took me around 8 hours to find out the problem. First I needed webpacker to manage my packs. So added to my rails app and then installed it
# Gemfile
gem 'webpacker'#Install
bundle install
rails webpacker:install
This creates a new app/javascript/packs -folder, where also a (new) application.js file can be found. There later I would import my function.
But first I needed to go the my address.html.erb and get the actual id, which was hidden and I had to inspect element in the browser. So this code bit should be as follows:
<divclass="row second 1"><divclass="column"><divclass="field wizard">
<%= f.label :street, class: 'required' %><br />
<%= f.text_field :street, class: 'form-control' %>
</div></div><divclass="column"><divclass="field housenumber">
<%= f.label :house_number, class: 'required' %><br />
<%= f.text_field :house_number, class: 'form-control' %>
</div></div></div><divclass="row second 2"><divclass="column"><divclass="field wizard">
<%= f.label :city, class: 'required' %><br />
<%= f.text_field :city, class: 'form-control' %>
</div></div><divclass="column"><divclass="field wizard zipcode">
<%= f.label :zip_code, class: 'required' %><br />
<%= f.text_field :zip_code, class: 'form-control' %>
</div></div></div>
So no definition of id's in the form. I deleted them.
Next step create a file app/javascript/packs/autocomplete.js
import places from'places.js';
constinitAutocomplete = () => {
var placesAutocomplete = places({
container: document.getElementById('user_street'),
templates: {
value: function(suggestion) {
return suggestion.name;
}
}
}).configure({
type: 'address'
});
placesAutocomplete.on('change', functionresultSelected(e) {
document.getElementById('user_city').value = e.suggestion.city || '';
document.getElementById('user_zip_code').value = e.suggestion.postcode || '';
});
};
export { initAutocomplete };
Now actually the places.js can be imported from my node_modules (which I installed before, following the instruction on algolia website.).
Last but not least, as I mentioned above, I went back to app/javascript/packs/application.js and imported my function:
import { initAutocomplete } from'./autocomplete';
initAutocomplete();
So now this works for me just fine! The address paerts are also inserted in the right fields of my form.
Post a Comment for "Algolia Places And Rails: Autocomplete Form"