lundi 21 janvier 2019

Rails: How does index option work for form select?

I am working on a checkout process where I have a shipping address and billing address. When both are identical the shipping address data is copied in the client through JavaScript into the billing address.

I have a problem with a select dropdown field, which displays a prompt on first load and invites to choose the billing country.

<%#= f.collection_select(:bill_to_land_id, Land.all, :id, :name, {:prompt => "select a country"}, {:id => 'order_bill_to_land'}) %>

Apparently, following the API documentation on FormOptionsHelper, I cannot rely currently on the index of the select option, since after choosing the billing country, navigating in the checkout process and returning to the billing address section the index count changed. This happens probably because the prompt is not displayed any longer.

:prompt - set to true or a prompt string. When the select element doesn’t have a value yet, this prepends an option with a generic prompt – “Please select” – or the given prompt string.

The main difference is that if the select already has a value, then :prompt will not show whereas the :include_blank always will.

<select id="order_bill_to_land" name="order[bill_to_land_id]"><option value="">select a country</option>
  <option value="1">Afghanistan</option>
  <option value="2">Aland Islands</option>
  <option value="3">Albania</option>

<select id="order_bill_to_land" name="order[][bill_to_land_id]"><option value="1">Afghanistan</option>
  <option value="2">Aland Islands</option>
  <option value="3">Albania</option>

Is there a way to maintain the prompt even after a value has been selected in order to still rely on the selectedIndex method in JS? I know there is an index option for select helper, but cannot find any documentation.

Aucun commentaire:

Enregistrer un commentaire