根据Rails应用程序中的选定选项显示文本

时间:2015-09-16 08:30:03

标签: javascript jquery ruby-on-rails

选择国家/地区的选项是

<%= f.select :country_id, options_for_select(Country.all.order(:name).map{ |c| [t(c.code2.to_sym, :scope => :countries), c.id] }, selected: @customer.try(:country).try(:id)), wrapper_html: {:class=>'form-control', id:"country_name"} %>

我有一个文本字段可以通过此

输入国家电话代码
<%= f.text_field :phone_country, :class=>"form-control", wrapper_html: {id: "telephone_code"} %>

我希望根据上一个选项中选择的国家/地区自动输入电话号码。我在数据库中有国家代码,我也理解我必须使用jQuery函数,但无法进一步。感谢。

1 个答案:

答案 0 :(得分:0)

$(".country_id").on('change', function(){
 $('.phone_country').val($(this).val());
});

当我们更改下拉列表的值时,将调用上述函数。

<%= f.select :country_id, options_for_select(Country.all.order(:name).map{ |c| [t(c.code2.to_sym, :scope => :countries), c.id] }, selected: @customer.try(:country).try(:id)), wrapper_html: {:class=>'form-control country_id', id:"country_name"} %>

<%= f.text_field :phone_country, :class=>"form-control phone_country", wrapper_html: {id: "telephone_code"} %>

更新:我尝试使用以下代码执行Ajax请求。但仍然无法弄清楚如何根据下拉列表插入数据。

  $('.country-id').on 'change', (e) ->
    $.ajax
      type: 'GET'
      url: '/new'
      data: 'country-id'
      success: (data) ->
        alert data
        return