在Rails管理员中使用Ajax更新文本区域

时间:2012-09-26 01:00:43

标签: ruby-on-rails ruby ajax

此代码段来自我的管理员。我在图像旁边有一个描述字段,以及一个如何在它下面看的样子。

现在它在页面刷新后工作但我希望它能够使用AJAX异步工作,因此当用户输入它时会更新textarea下面的演示。enter image description here

#This is where you update the field
<tr><th>Description</th><td><%= f.text_area(:description) %></td></tr>

    <tr><th>Demo</th>
      <td>
      <% if @org.images.present?  %>
          <table border="0">
            <tr>
            <td>
            <%= featured_image_tag(@org, :type => 'organization')  %>
            </td>
            <td style="vertical-align:top;padding-top:5px;padding-left:5px;">
            <span class="font-avebook"><%= @org.description  %>  </span><br> 
            </td>
            </tr>
            </table>
          <% else   %>    
        You need to assoicate an image first before seeing the demo!
      <% end  %>    
    </td>
</tr>

1 个答案:

答案 0 :(得分:1)

要在您撰写的同时让文字直接显示在下方,您需要使用jQuery Keyup事件来提交数据。但是,在每个keyup之后提交数据不是最好的主意。如果你想获得这种效果,为什么不用jQuery做整个事情而不实际保存数据。您可以在每个键盘后将输入的内容附加到图像旁边的元素。我在下面做了一个小演示。

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <input type="text" id="copy_text">
  <div id="mirror_paragraph"></div>
<script>
    $("#copy_text").keyup(function () {
      var txt = $("#copy_text").val();
      $("#mirror_paragraph").html(txt);
    });
</script>

</body>
</html>​​​​​​​​​​​

改编自您的代码:

<tr>
  <th>Description</th>
  <td><%= f.text_area(:description), :id => "copy_text" %></td>
</tr>

<tr>
  <th>Demo</th>
  <td>
    <% if @org.images.present? %>
        <table border="0">
          <tr>
            <td>
              <%= featured_image_tag(@org, :type => 'organization') %>
            </td>
            <td style="vertical-align:top;padding-top:5px;padding-left:5px;">
              <span class="font-avebook" id="mirror_paragraph"><%= @org.description %>  </span><br>
            </td>
          </tr>
        </table>
    <% else %>
        You need to assoicate an image first before seeing the demo!
    <% end %>
  </td>
</tr>

<script>
    $("#copy_text").keyup(function () {
      var txt = $("#copy_text").val();
      $("#mirror_paragraph").html(txt);
    });
</script>