我正在使用city-state gem(https://github.com/loureirorg/city-state)并尝试创建一个选择状态的表单,然后使用javascript动态更新城市,具体取决于所选的状态但不起作用。
我的html表单是:
<select id="states-of-country" name="project[state]">
<option id="no-state" value="" selected>Select Your State</option>
<% CS.states(:us).each do |key, value| %>
<option value="<%= value %>" id="<%= key %>"><%= value %></option>
<% end %>
</select>
<select id="cities-of-state" name="project[city]" class="form-control form-control-small" required>
<option value="" selected>Select Your City</option>
</select>
javascript是:
$(document).on('change', '#states-of-country', function(e) {
var cities_of_state, input_state, state;
input_state = $(this);
cities_of_state = $('#cities-of-state');
state = this.options[e.target.selectedIndex].id;
if (state === 'no-state') {
return cities_of_state.html('');
} else {
$.ajax({
url: '/cities/' + $(this).children(':selected').attr('id'),
success: function(data) {
var opt;
opt = '<option value="" selected>Select Your City</option>';
if (data.length === 0) {} else {
data.forEach(function(i) {
opt += '<option value="' + i + '">' + i + '</option>';
});
cities_of_state.html(opt);
}
}
});
}
});