0

I am trying to generate a select_tag when the user clicks on a particular element. I have this JS in my page :

  $(document).ready(function(){
    $("#add_hotel").click(function(){
      $(".new_hotels").append('<%=select_tag "dash_select", options_for_select(session[:user_hotel_list].collect{ |hotel| [hotel["name"], hotel["id"]] }) %>');
    })
  })

The resulting code looks like this :

 <script>
  $(document).ready(function(){
    $("#add_hotel").click(function(){
      $(".new_hotels").append('<select name="dash_select" id="dash_select">
<option value="31">Plaze</option>
<option value="30">dndjd</option></select>');
    })
  })

  </script>

but I get Uncaught SyntaxError: Unexpected token ILLEGAL.

---EDIT---

The line with the error is this one :

  $(".new_hotels").append( '<select name="dash_select" id="dash_select"><option value="31">Plaze</option>
<option value="30">dndjd</option></select>');

---EDIT---

Here's a picture of the exact line where I get the errorenter image description here in the console:

I noticed that when there is only one element in session[:user_hotel_list], the code works fine. As was suggested it could be a problem linked to special hidden characters and copy paste issue, but I tried to write letter by letter the code and I still get this error...

David Geismar
  • 3,152
  • 6
  • 41
  • 80

2 Answers2

0

You can create a file named your_js_file.js.erb. Then you will be able to use Rails tags inside of it.

0

Why don't you store your interpolation first in a variable and then put that in append? It seems like the code your interpolation generates does work if it's all in one line. I ran it in the inspector and if it's all in one line it does run fine. Anyhow try that. Hope it helps.

      $(document).ready(function(){
        $("#add_hotel").click(function(){
          var hotels = <%=select_tag "dash_select", options_for_select([["all hotels", "all"]]+ session[:user_hotel_list].collect{ |hotel| [hotel["name"], hotel["id"]] }) %>
          $(".new_hotels").append(hotels);
        })
      })
rii
  • 1,578
  • 1
  • 17
  • 22
  • Your trick doesnt work. The code actually works if there's only one element in ```session[:user_hotel_list```but as soon as there is two elements I get the error back – David Geismar Mar 01 '16 at 18:32