Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveAdmin dynamic select_tag based on other selections

Currently I have a form that looks like:

form_tag(manage_titans_admin_collection_path(collection), method: :post) do
  label_tag('Race:') +
  ' ' +
  select_tag(:race, options_for_select(Collectible.where(primary_type: 'cpt_golem').order('race asc').uniq.pluck(:race))) +
  ' ' +
  label_tag('Stage:') +
  ' ' +
  select_tag(:stage, options_for_select(1.upto(4))) +
  ' ' +
  label_tag('Level:') +
  ' ' +
  text_field_tag(:level, 1, style: 'width: 100px') +
  ' ' +
  submit_tag('Submit')
end

I want to change it such that the :level selection is a select_tag of consecutive numbers, which change according to the :stage selected. For example, if stage is 1, I want to show the levels 1-20, but if stage 2 is selected, I want to show levels 20 to 40.

Thanks for your time!

like image 710
Kevin Avatar asked Mar 15 '26 00:03

Kevin


1 Answers

In the end the helper tags you are using translate to html so I would use a javascript function with jquery:
Assuming that you will have in your page a:

<select name="stage" id="stage">
   <option value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
   <option value="4">4</option>
</select>

And a:

<select name="level" id="level"></select>

The function would be something like this:

$(document).ready(function(){
    $('#stage').on('change', function() {
        var level = $("#level");
        var value = this.value;
        level.empty();
        if (value == 1) {
            init = 1;
            final = 20;
        } else if(value == 2) {
            init = 21;
            final = 40;
        } else if(value == 3) {
            init = 41;
            final = 60;
        } else if (value == 4) {
            init = 61;
            final = 80;
        }
        var cont = 0;
        for(var i=0; (init+cont)<=final; i++) {
            level.append('<option value="'+(init + cont)+'">'+(init + cont)+'</option>')
            cont++;
        }
    });
    $('#stage').change();
});

If you want to change the levels just update the numbers in the function. Or add another condition.
Hope it helps.

like image 130
danielR Avatar answered Mar 16 '26 13:03

danielR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!