In my Rails Application I have a Country Select Option Drop down list using the country_select gem,and next to the country select drop down there is another dropdown to display the states in "US" like the code bellow:
CODE OF COUNTRY SELECT DROP DOWN
<div class="row">
<div class="form-group">
<%= f.label :country,'Country', class:"control-label"%>
<%= f.country_select(:country , {priority_countries: [ "US"]} ,{class: "form-control"}) %>
</div>
</div>
CODE OF STATE SELECT DROP DOWN
<%= f.label :state,'State', class:"control-label" , style: "color: black;"%>
<%= f.select( :state, options_for_select(us_states), {}, {class: "form-control"}) %>
Here us_states method is defined in application_helper.rb file like bellow:
def us_states
[
['Alabama', 'AL'],
['Alaska', 'AK'],
['Arizona', 'AZ'],
...............etc
]
end
Here the default selected country is "US", but if the user select any other country from the country select drop down then I want make the state select drop down into a normal text field not a drop down list . How can I make the state select drop down into a text field if the user select a country other than US ? And if the selected country is US the state section must stay as a drop down ?
I would recommend to add both Text Field and State dropdown initially and toggle them depending on Country value.
<%= f.label :state,'State', class:"control-label" , style: "color: black;"%>
<%= f.select( :state, options_for_select(us_states), {}, {class: "form-control"}) %>
<%= f.text_field :state,'', class: "form-control",:style=>"display:none"%>
Now add toggle logic in jquery
<script type='text/javascript'>
$("#country_drop_down_id").change(function(){
if($(this).val()=='US'){
$('#state_drop_down_id').show();
$('#state_text_field_id').hide();
}else{
$('#state_drop_down_id').hide();
$('#state_text_field_id').show();
}
});
</script>
Replace country_drop_down_id , state_drop_down_id , state_text_field_id
with corresponding ID selector.
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.