jquery - Structuring a Rails app with javascript -


simple question,

in rails app, made scaffold

rails g scaffold post title:string body:string 

i want add simple condition in front-end javascript

if @posts exists, alert("exist") else, alert("no posts")

i can add scripts inside views/posts/index.html.erb

<script>     $(function () {         if (<%=@posts.length%> > 2)             alert("exist");         else             alert("no posts");     }); </script>  <h1>listing posts</h1>  <table>   <thead>   <tr>     <th>title</th>     <th>body</th>     <th></th>     <th></th>     <th></th>   </tr>   </thead>    <tbody>   <% @posts.each |post| %>       <tr>         <td><%= post.title %></td>         <td><%= post.body %></td>         <td><%= link_to 'show', post %></td>         <td><%= link_to 'edit', edit_post_path(post) %></td>         <td><%= link_to 'destroy', post, method: :delete, data: {confirm: 'are sure?'} %></td>       </tr>   <% end %>   </tbody> </table>  <br>  <%= link_to 'new post', new_post_path %> 

the problem is,

<script>     $(function () {         if (<%=@posts.length%> > 2)             alert("exist");         else             alert("no posts");     }); </script> 

i want seprated individual js file.

so, have put code in

assets/javascripts/posts.js    $(function () {             if (<%=@posts.length%> > 2)                 alert("exist");             else                 alert("no posts");   }); 

but in here, cannot use <%=%> rails view stuff :(

is there solution?

you add data attribute table post count, , perhaps class listen on pages. like:

# view body class=controller_name   table data-posts-count=@posts.length 

.

# js $("body.posts").load(function() {   count = $(this).data("posts-count")    if count > 2     alert("exist");   else     alert("no posts"); }); 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -