簡體   English   中英

ActiveAdmin動態select_tag基於其他選擇

[英]ActiveAdmin dynamic select_tag based on other selections

目前我的表格看起來像:

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

我想改變它,使得:level選擇是連續數字的select_tag ,它根據所選擇的:stage而改變。 例如,如果stage為1,我想顯示1-20的級別,但是如果選擇了stage 2,我想顯示級別20到40。

謝謝你的時間!

最后你使用的幫助器標簽轉換為html所以我會使用jquery的javascript函數:
假設你的頁面中有一個:

<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>

並且:

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

功能將是這樣的:

$(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();
});

如果要更改級別,只需更新函數中的數字即可。 或者添加另一個條件。
希望能幫助到你。

與@danielR相同的概念,但實現更清晰:

(也假設為@danielR,第2階段的范圍應該是21-40而不是20-40。)

HTML

<select id='stage'>
    <option></option>
    <option value='1'>1</option>
    <option value='2'>2</option>
    <option value='3'>3</option>
    <option value='4'>4</option>
</select>
<select id='level'><option></option></select>

jQuery的

function addOptions(selector, modifier){
    $(selector).each(function(){ 
        $(this).find('option').remove().end().append('<option></option>');
        start = ((modifier - 1) * 20) + 1;
        end = modifier * 20;
        for (i = start; i <= end; i++){
            $('<option>').text(i).val(i).appendTo($(this));
        }
    });
}


$(document).ready(function(){    
    $('#stage').on('change',function(){
        addOptions('#level', parseInt($(this).val(),10));
    });
});

jsFiddle示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM