Search code examples
javascriptjqueryruby-on-railsajaxace-editor

How do I use form_for with non-input elements?


I want to use Ace Editor in my view for creating a post object, instead of a textarea, but Ace Editor requires the use of a <div> to contain its content. I'm new to Ruby on Rails 4 I'm trying to figure out how I can securely submit user input using the Ace Editor and redirect the user to the page that shows the post after it's been submitted. Here's my current form for submitting a post that does NOT yet use the Ace Editor <div>...

<%= form_for(@post) do |f| %>
  <div class="field">
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :description %><br>
     <!-- I'd like to replace this text_area with the ace editor div-->
    <%= f.text_area :description %> 
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

How can I replace the f.text_area element with a <div> and include it's contents in the form's post request?


Solution

  • With the new version of ace you can use textarea too

    see http://jsbin.com/jodeyugenu/1/edit

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>JS Bin</title>
      <script src="http://ajaxorg.github.io/ace-builds/src/ace.js"></script> 
      <style>
        #ta { position: absolute; top: 0; left: 0; right: 0; bottom: 0;}
      </style>
    </head>
    <body>
      <form id="myForm">
        <div style="position:relative;height:200px;width:300px">
          <textarea id="ta">text</textarea> 
        </div>
        <input type="submit" value="submit" >
      </form>
    </body>
    <script>
      var textareaEl = document.getElementById("ta");
      // update textarea value before submitting
      var form = textareaEl.form
      form.addEventListener("submit", function() {    
        textareaEl.style.visibility = "hidden"
        textareaEl.value = editor.getValue()
        form.appendChild(textareaEl)
      });
      // create editor and set id for it
      editor = ace.edit(textareaEl)
      editor.container.id = "ta"
      // add a keyboard shortcut for submitting
      editor.commands.addCommand({
        name: "submit",
        exec: function() {
          form.submit()
        },
        bindKey: "Ctrl-Enter"
      })
    </script>
    </html>