首页 > 解决方案 > 如何获取 Rails 表单中文本字段的新值?

问题描述

<%= form_for(@mymodel, remote: true, html: { id: 'match_form' }) do |f| %>
   <%= f.text_field :match_id, style: "width:82px" %>

   <%= f.submit 'Save', class: 'btn btn-primary', id: 'match_submit', style: "width:38px;padding:0px" %> 
   <%= button_tag 'Cancel', class: 'btn btn-secondary', id: 'match_cancel', style: "width:52px;padding:0px" %>
<% end%>


<script type='text/javascript'>
    $(function() {
      $(document).on("click", "#match_submit", function(event){
        $.ajax('my_controller_method', {
          type: 'GET',
          dataType: 'script',
          data: {
            mid: $("#").val(),  // How can I get the new value entered in 'match_id' textfield here?
          },
          error: function(jqXHR, textStatus, errorThrown) {
          return console.log("AJAX Error: " + textStatus);
        }
      });      
    });
  </script>

我有上面显示的表单和 JavaScript 块。

如何获取在 JavaScript 代码的“match_id”文本字段中输入的新值?

标签: javascriptruby-on-rails

解决方案


您需要了解 ERB 是一个存在于服务器上的模板,然后被编译为 HTML(意思是,所有 ERB 代码完全消失),然后将生成的 HTML 发送到浏览器,然后执行 JS 代码。

JS 只会看到并使用生成的 HTML。它不知道是否存在 ERB 或 PHP 或任何用于生成其工作的 HTML 的模板语言。

您的 ERB 模板的结果将是<input id="debit_match_id">,因此在 JS/jQuery 中选择它的正确方法是$("#debit_match_id").


推荐阅读