0

I'd like to pass the selected value to the hidden field

In my view, I have:

<div class="field">
 <label class="label">Category</label>
   <div class="select">
      <%= f.select(:category_id, 
                    options_for_select(@categories.map { |c| [c.name, 
                                                              c.id,
                                                              {:category_slug=>c.slug}] 
                                                       }, 
                    selected: @product.category_slug )
                  ) %>
      <%= f.hidden_field :category_slug, value: @product.category_slug %>
   </div>
</div>


I pass this {:category_slug=>c.slug} or @product.category_slug value to the hidden field as follow script but it doesn't work

<%= f.hidden_field :category_slug, value: @product.category_slug %>

How can I pass the selected value to the hidden field? Thanks.

Romeo
  • 329
  • 4
  • 17

1 Answers1

1

To dynamically update the page after it has been rendered you would need to use JavaScript to handle the changes on the client side.

Assuming your generated HTML looks something like this...

<select name="product[category_id]" id="category_id">
  <option category_slug="slug" value="1">NAME</option>
</select>

This JavaScript will attach a listener to the "change" event of the select box.

When the elect box is changed it will fire the function and grab the "category_slug" attribute of the selected option, then assign it to the value attribute of your hidden field.

(You can uncomment the alert to debug - it should show a pop up window with the selected category_slug value each time you chaneg the select box)

window.onload = function () {
  document.getElementById("category_id").addEventListener("change", function(e) {
    var category_slug = this.options[this.selectedIndex].getAttribute('category_slug');
    // alert(category_slug);
    document.getElementById("category_slug").value = category_slug;
  });
};

This is vanilla JavaScript, but you could easily use JQuery if you prefer.

The only other thing I would mention is that if you might want to consider making the non-standard "category_slug" attribute into a data attribute (see: are custom html attributes without data-* prefix a valid attribute?) e.g:

<%= f.select(:category_id, 
                    options_for_select(@categories.map { |c| [c.name, 
                                                              c.id,
                                                              {:data => {:category_slug=>"slug"}}] 
                                                       }, 
                    selected: @product.category_slug )
                  ) %>

This would mean you need to change this line in the JavaScript

var category_slug = this.options[this.selectedIndex].getAttribute('data-category-slug'); // (NB: underscore becomes a dash!)

sgbett
  • 348
  • 3
  • 15