0

I want to load a form only if javascript is enabled.

I was hoping to do it like this:

<% if javascript_enabled? %>
...form code...
<% else %>
  Please enable javascript
<% end %>

Is something like this possible?

pejmanjohn
  • 1,057
  • 3
  • 12
  • 26
  • 1
    possible duplicate of : http://stackoverflow.com/questions/2315648/check-if-javascript-is-enabled-serverside-with-rails – Saurabh Apr 30 '14 at 21:34
  • 1
    also here: http://stackoverflow.com/questions/745613/ruby-on-rails-javascript-detection – Eyeslandic Apr 30 '14 at 21:35

1 Answers1

1

The problem with your approach is that only the browser knows if Javascript is enabled or not, and you try to check if is is enabled with rails (which is server interpreted code). There are several workarounds to solve this problem, but I usually do the following in my Rails apps:

  1. Include <noscript>Please enable Javascript</noscript> at the top of the page content.
  2. Set display:none or visibility:hidden attribute style in the form you want to show only when Javascript is enabled.
  3. Include Javascript code which change the display style attribute to "block" or the visibility one to "visible" when the page is loaded.

This way your form is only showed when Javascript is enabled and the message requesting to enable Javascript is showed only when Javascript is not enabled.

Finally, you can use Rails code to make all this as simple as possible, of course.