简体   繁体   中英

Display text based on a selected option in Rails app

The option to select the country is through

<%= 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"} %>

And I have a text field to enter the country telephone code through this

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

I want the telephone code to be entered automatically based on the country selected in the previous option. I have the country codes in the database and I also understand I have to use jQuery function, but couldn't get further. Thanks.

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

The above function will be called when we change value of dropdown.

<%= 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"} %>

Update: I tried to do a Ajax request with the following code. But still couldn't figure out how to insert data based on the drop-down.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM