Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Automatizando a seleção de Municípios/UF
/**
* Campos de state com data-cities="nome_do_select_de_cidades"
* funcionarão automaticamente
*/
$('[data-cities]').change(function() {
var $select = $('select[name="' + $(this).attr('data-cities') + '"]');
var $value = $('input[type=hidden][name="' + $(this).attr('data-cities') + '"]');
if (!$select.length) {
return;
}
// Precisa selecionar um valor
if(!this.value) {
$select.html('').append('<option value="">Selecione a UF</option>');
return;
}
$select.attr('disabled', 'true');
$.getJSON('/cities/all_by_state_id/' + $(this).val(), function(data) {
// Popula os dados no select de cidades
$select = $select.html('').append('<option value="">Selecione</option>');
$.each(data.data.cities, function(i, val){
$select.append('<option value="' + val.id + '">' + val.name + '</option>');
});
$select.removeAttr('disabled');
// Verifica se já tem uma opção pré-determinada
var value = $select.attr('data-value') || $value.val();
if (value) {
$select.find('option[value=' + value + ']')
.attr('selected', true)
.removeAttr('data-value');
}
});
}).each(function() {
var $cidade = $('select[name="' + $(this).attr('data-cities') + '"]').html('').append('<option value="">Selecione a UF</option>');
var value = $cidade.attr('data-value');
if (this.value || value) {
$(this).change();
}
});
def get_form_builder_field_name(object_name, field_name)
if object_name.is_a?(ActionView::Helpers::FormBuilder)
object_name = object_name.object_name
end
"#{object_name}[#{field_name.to_s.sub(/\?$/, '')}]"
end
class CitiesController < ApplicationController
def all_by_state_id
uf = params[:id]
cities = City.joins(:state).where('states.id' => uf).select('cities.id, cities.name')
render :json => { data: { cities: cities } }
end
end
<div class="control-group">
<%= f.label :state_id, :class => 'control-label' %>
<div class="controls">
<%= f.collection_select :state_id, State.all, :id, :name, { :prompt => true }, :data => { :cities => get_form_builder_field_name(f, :city_id) } %>
</div>
</div>
<div class="control-group">
<%= f.label :city_id, :class => 'control-label' %>
<div class="controls">
<%= f.hidden_field :city_id %>
<%= f.select :city_id, [] %>
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.