0

I have a form with a Jquery plugin requirement that creates a form input field with a type of Facebook-autocomplete kind of style:

<%= javascript_include_tag "form_prettify_library" %>

<div class="box">
  <ul id="first_form" class="tagit">
      <li class="prettify-new"></li>
  </ul>
    <%= form_for @brand do |f| %>
    <%= f.hidden_field :tag_list, :value => @brand.tags_from(current_user).join(", "),
                                  :id => "mytaglist" %>
    <%= f.submit "Add tags" %>
    <%= f.error_messages %>
    <% end %>
</div>

It works well, however without JavaScript the form doesn't work because the form above only has a hidden_field and no visible entry field (the entry field is created by the plugin inside of the tags), and I need this to work without JavaScript on mobile devices. Is there any way to show the code above if JavaScript is loaded, otherwise the code below will be displayed if it isn't?

<div class="box">
  <%= form_for @brand do |f| %>
    <%= f.label :tag_list, "Your tags" %>
    <%= f.text_field :tag_list, :value => @brand.all_tags_list %>
    <%= f.submit "Add tags" %>
  <% end %>
</div> 

1 Answer 1

3

Yes, use css to hide it by default, and add a class to the site when js is enabled

html

<body class="no_js">
<script type="text/javascript">
(function() {
   var body = document.getElementsByTagName("body")[0];
   body.className = body.className.replace(/\bno_js\b/, " js ")
}())
</script>

css

.no_js .jsForm,
.js .no_jsForm  {
   display:none;
}

.js .jsForm,
.no_js .no_jsForm  {
   display: block;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Although this is feasible, I'd like a more Rails-like solution.
This would be the standard way of achieving what you need. Getting rails (server side) to detect if js is available (client-side) isn't possible without sending another request back to the server, so the only alternative is to serve the non js form, and get the js form via ajax if it's available, which would be slower overall. I'm not sure what you mean by a more rails way of handling it (I don't know Ruby or Rails), but your server side app can't find out in advance if js is enabled - the browser doesn't send this information in a http request.
I did want some kind of server-side detection, perhaps a WURFL implementation that sniffs JS compatibility. This will have to suffice then.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.