我正在使用内联表单让用户将数据提交到表格(请注意,我使用 CSS 而不是 html 表格来实现这一点)。当模型中的验证返回错误时,我想使用 Bootstrap 错误类突出显示输入字段,并将错误消息放在适当的表单字段下方。我正在使用 AJAX 提交表单。
我遇到了问题,这是我到目前为止所遇到的:
控制器:
def create
@travel = Travel.new(params[:travel])
@travel[:user_id] = current_user.id
convert_date # and return
if @travel.save
flash[:notice] = "Successfully saved trip"
@travels = Travel.where("user_id = ?",current_user)
respond_to { |format| format.js }
end
end
JS视图:
<% if @travel.errors.any? %>
<% @travel.errors.full_messages.each { |msg| logger.debug(msg) } %>
<% @travel.errors.messages.each do |k,v| %>
<% logger.debug("#tf_#{k}") %>
$(<%= "#tf_#{k}" %>).insertAdjacentHTML("afterbegin","<span class="control-group error"><span class="controls">");
$(<%= "#tf_#{k}" %>).insertAdjacentHTML("beforeend","</span></span>");
$(<%= "#error_#{k}" %>).val("<%= "#{k} #{v}" %>");
<% end %>
<% else %>
$(":input:not(input[type=submit])").val("");
$("#travels_list").html("<%= escape_javascript( render(:partial => "travels") ) %>");
<% end %>
形成部分:
<%= form_for @travel, :remote => true, :html => {:class => "form-inline", :id => "new-travel-form"} do |f| %>
<div class="row-fluid">
<span id="tf_city"><%= f.text_field :city, :placeholder => "London, UK", :class => "span3" %></span>
<span id="tf_arrive_date"><%= f.text_field :arrive_date, :class => "span2" %> </span>
<span id="tf_leave_date"><%= f.text_field :leave_date, :class => "span2" %> </span>
<span id="tf_notes"><%= f.text_field :notes, :placeholder => "e.g. staying at the Hilton", :class => "span3" %></span>
<%= f.submit "save", :class => "btn btn-primary span1" %>
</div>
<% end %>
<div class="row-fluid error" id="error_expl">
<span id="error_city" class="help-inline span3"></span>
<span id="error_arrive_date" class="help-inline span2"></span>
<span id="error_leave_date" class="help-inline span2"></span>
<span id="error_notes" class="help-inline span3">test</span>
</div>
JS 中的logger.debug
正在触发,所以我知道错误正在传递给 JS,但insertAdjacentHMTL()
似乎没有工作。