Search code examples
javascriptjqueryhtmlruby-on-railsturbolinks

Looping expression in HTML div tag to work with Javascript


I am doing a Ruby on rails project where I am trying to loop the variables in the html form so that I don't need to manually write so much code. However, I realised that if I put expression to be evaluated in the id tag, the JS code will not work. for example, <div class="field" id="barcode_type1"> works, but <div class="field" id="barcode_type#{i}"> where i is from 1 to 10 does not work.

I am guessing evaluating an expression in html will not be called on Javascript side, I am also suspecting that maybe turbolinks will not wait for the id tag to be evaluated. So my suspicion is either I cannot use expresion in id tag, or that I need to change the turbolinks.

in my html.erb

<% for i in 1..10 %> 
   <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> 
  </div>

in my .js file

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

....


Solution

  • Try to change this:

    <div class="field" id="type#{i}">
    

    to this:

    <div class="field" id="type<%= i %>">
    

    because <div class="field" id="type#{i}"> is a plain HTML code, RoR doesn't change anything here and your HTML page looks exactly the same way as you wrote.