簡體   English   中英

在Rails上使用ruby循環html表單erb

[英]Loop in a html form erb using ruby on rails

我想建立一個表單,其中字段名稱是type1,type2,type3 ...到type10,size1,size2,size3 ...到size10等。

我需要在文本字段中呈現它們,以便用戶可以為其輸入值。 我不想手動鍵入它們中的每一個,因為必須有一些可以使用的循環迭代器。 我知道每種方法,但是我只想創建一個循環以將type1循環到type10。 我該如何實現?

 <div class="field" id="type1">
    <%= f.label :type1 %>
    <%= f.select :type1 ,['text','barcode']%>
 </div> 

 <div class="field" id="type2">
    <%= f.label :type2 %>
    <%= f.select :type2 ,['text','barcode']%>
 </div> 

<div class="field" id="barcode_type1">
    <%= f.label :barcode_type1 %>
    <%= f.text_field :barcode_type1 %>
    </div> 

<div class="field" id="barcode_type2">
    <%= f.label :barcode_type2 %>
    <%= f.text_field :barcode_type2 %>
    </div> 

有什么建議么?

更新:

$(document).on('turbolinks:load', function(){


if ($('#type1').find('option:selected').val() != "barcode")
  {
   $('#barcode_type1').hide();
   $("#barcode_type1").attr('disabled','disabled');
  }
  else
  {
     $("#barcode_type1").removeAttr('disabled');
     $('#barcode_type1').show();
  }

$('#type1').on('change', function(){
  if ($('#type1').find('option:selected').val() != "barcode")
  {
   $('#barcode_type1').hide();
   $("#barcode_type1").attr('disabled','disabled');
  }
  else
  {
     $("#barcode_type1").removeAttr('disabled');
     $('#barcode_type1').show();
  }
})

});

如果我將div id設置為id =“ type1”,則JS運行良好。 如果在循環中使用“ type#{i}”,則JS停止工作。 有沒有解決的辦法。 我也想在Javascript中將類型1循環到類型10,將條形碼_類型1循環到條形碼_類型10。 有沒有辦法有效地做到這一點。

您可以使用:

<% for i in 1..10 do %>
  <div class="field" id="type#{i}"
    <%= f.label "type#{i}" %>
    <%= f.select "type#{i}", ["text", "barcode"] %>
  </div>
<% end %>

您還可以使用您提到的每個循環,但不能使用for循環。

<% (1..10).each do |i| %>
    <div class="field" id="type#{i}">
        <%= f.label "type#{i}" %>
        <%= f.select "type#{i}" ,['text','barcode']%>
    </div> 
    <div class="field" id="barcode_type#{i}">
        <%= f.label "barcode_type#{i}" %>
        <%= f.text_field "barcode_type#{i}" %>
    </div> 
<% end %>

暫無
暫無

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

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