I'm stuck at one task and have no idea how to move on. Any comments would be highly appreciated! (I'm very new to Javascript and jQuery).
I'm implementing the ability to mark a building on google maps during creation or editing the building (the same form for both).
So my form in .html.haml document has 2 fields for choosing a country and a city. The city field is disabled as long ad the country is not chosen. Both fields saves ids for country and city (not names!).
= select_tag 'building[country_id]', options_for_select(Country.all.map{|c| [c.name, c.id]), onchange: "getLocationObjects ($(this).val(), '#{cities_path}')"
- if building.country
= select_tag 'building[city_id]', options_for_select(building.get_countries.cities.map{|c| [c.name, c.id]}, building.get_city.id), include_blank: "Choose city"
- else
= select_tag 'building[city_id]', options_for_select([["Choose country", '']]), disabled: true
But for marking a building on google maps I need a city name, not id (don't say "Then save it in select tag instead of id", I need an id in other parts of an app).
So I use a jQuery to save a name of a city:
:javascript
$(document).ready( function () {
$('#building_city_id').change(function() {
var option = $(this).find('option:selected').text();
return option;
});
});
That's where the first problem occurs: when I edit a building that already has a country specified, a jQuery function saves a city name just fine. But if I choose another country from the list it doesn't work anymore.
Second problem: all the code for google mapping is located in .js file. So how do I call a Javascript variable created in .html.haml file here?