0

I am working with Ruby on Rails, JavaScript and Simple Form and I have a problem adding Ruby code into a function in JavaScript.

My source code is:

$('#add_taxo').on('click',function() { document.getElementById('okok').innerHTML += '<li class="list-group-item"> <%= taxonomies_select_tag( 'statistic[taxonomy]', Folders::Taxonomy, Folders::Taxonomy::TAXONOMY_KEY, level: 3, path: 'folders/taxonomies', include_blank: true, class: 'required form-control test_taxo')%> </li>'; alert("lklk"); }); 

This code doesn't work.

    3 Answers 3

    1

    You can only use ruby code through the view/*.js/coffee.erb files via ajax. You can't use ruby in plain js/coffeescript files. If you need to pass data from the controller to the js side, then pass them through hidden field tags in your view through data attributes.

    2
    • Duplicate of stackoverflow.com/questions/45806146/…CommentedAug 28, 2017 at 16:12
    • This is not duplicate code. That example does not explain that the code in context, needs to handled through an ajax response within the 'views/*js.erb', and not the assets.
      – Kao
      CommentedAug 28, 2017 at 17:13
    0

    Try escaping the javascript in the ruby code, like this:

    document.getElementById('okok').innerHTML += '<li class="list-group-item"> <%= j(taxonomies_select_tag( 'statistic[taxonomy]', Folders::Taxonomy, Folders::Taxonomy::TAXONOMY_KEY, level: 3, path: 'folders/taxonomies', include_blank: true, class: 'required form-control test_taxo'))%> </li>'; 

    You can use either escape_javascript(...) or j(...) (as in the example).

    1
    • @youssefhassoun Do you get any errors on either server logs or browser console?
      – Gerry
      CommentedAug 21, 2017 at 22:49
    0

    make sure extension is .js.erb and it's part of views folder.

    If you want to do it through plain js then pass those variables through html, for eg: hidden fields, html tag properties.

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.