javascript - How to combine two select fields in a form -


i'm trying combine values of 2 select fields in form single variable before submitting form.

here of code:

in new.html.erb (for ror):

<%= form_for :character, url: characters_path, method: :post |f| %>   <p>      <%= f.label :alignment %><br>      <%= f.select :alignment_lr, options_for_select([" ","chaotic","neutral","lawful"], disabled: " ", selected: " ") %>      <%= f.select :alignment_ud, options_for_select([" ","good","neutral","evil"], disabled: " ", selected: " ") %>   </p> <% end %> 

this generates following html:

<p>   <label for="character_alignment">alignment</label><br>   <select id="character_alignment_lr" name="character[alignment_lr]">     <option disabled="disabled" selected="selected" value=" "> </option>     <option value="chaotic">chaotic</option>     <option value="neutral">neutral</option>     <option value="lawful">lawful</option></select>   <select id="character_alignment_ud" name="character[alignment_ud]">     <option disabled="disabled" selected="selected" value=" "> </option>     <option value="good">good</option>     <option value="neutral">neutral</option>     <option value="evil">evil</option></select> </p> 

how can combine values selected :alignment_lr , :alignment_ud equal alignment.value = alignment_lr.value + ' ' + alignment_ud.value?

i open using javascript or jquery in order resolve this.

it's not necessary use scripting @ all. appear have no real interest in keeping components of alignment variable separate fields in model, short answer is: don't it.

you can use virtual attributes record value in form , apply logic in model create actual value gets saved database via activerecord. virtual attributes allows form have fields not directly correspond fields in model.

  1. create migration drops "alignment_lr" , "alignment_ud" columns , replaces them single column "alignment." ideally, have database normalized in such way every alignment combination saved alignments table, , you'd saving key, rather dynamically generated string, different issue;

  2. in character.rb model, add attr_accessor line:

    class character < activerecord::base      attr_accessor: :alignment_lr, :alignment_ud 
  3. in characters_controller.rb file, add :alignment_lr , :alignment_ud strong params (character_params method)

  4. you can still write f.select statements have them.

  5. in characters_controller.rb create method:

    @character.combine_alignment(@character.alignment_lr, @character.alignment_ud) 
  6. in character.rb, add combine_alignment method:

    def combine_alignment(left_right, up_down)    return "#{left_right} #{up_down}" end 

Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -