Tag: Rails3/Ajax
<div id='result'>現在時刻: <%= Time.now %></div> <%= link_to '更新', {:action => 'upanel'}, :remote=>true %>
def upanel @time = Time.now.to_s end
$('#result').html( "<%= escape_javascript('現在時刻: ' + @time) %>" );
<h1>都道府県の絞り込み</h1> <%= form_tag({:action => 'result'}) do %> <%= select_tag "pref_id", options_for_select(@prefectures.map{|obj| [obj.name, obj.id]}, params['pref_id']), :prompt => "選択してください" %> <%= render :partial => 'select_city' %> <%= submit_tag '実行' %> <% end %> <h1 id="result">結果</h1> <script type="text/javascript"> $(function(){ $('#pref_id').change(function(){ var pref_id = $("#pref_id").val(); $.get("city_select?pref_id=" + pref_id); }) }); </script>
<%= select_tag "city_id", options_for_select(@cities.map{|obj| [obj.name, obj.id]}, params['city_id']), :prompt => "選択してください" %>
class Prefecture def initialize @cities = [] end attr_accessor :id, :name attr_accessor :cities end class City attr_accessor :id, :name end def upanel @time = Time.now.to_s end def init(pref_id) p1 = Prefecture.new p1.id = 1 p1.name = '東京' p2 = Prefecture.new p2.id = 2 p2.name = '埼玉' p3 = Prefecture.new p3.id = 3 p3.name = '神奈川' @prefectures = [p1, p2, p3] c11 = City.new c11.id = 11 c11.name = '浅草' c12 = City.new c12.id = 12 c12.name = '八王子' p1.cities = [c11, c12] c21 = City.new c21.id = 21 c21.name = '川口' c22 = City.new c22.id = 22 c22.name = '所沢' p2.cities = [c21, c22] c31 = City.new c31.id = 31 c31.name = '横浜' p3.cities = [c31] pref = @prefectures.find{|pref| pref.id == pref_id} @cities = pref.cities params[:pref_id] = pref_id params[:city_id] = pref.cities[0].id end def select init(1) end def city_select init(params[:pref_id].to_i) end
$("#result").html("<%= params[:city_id] %>"); $("#city_id").html("<%= escape_javascript(render :partial => 'select_city', :pref_id => params[:pref_id]) %>");