我想执行一个检查,以便使用java/coffee-script为我的个人档案模型的引导表单中的字段输入提供即时验证反馈。我目前的解决方案正在工作,但感觉相当笨拙,我想改进它。通过ID访问form_group div
下面是我正在做的一些代码示例。
应用程序/视图/型材/ _form:
<%= bootstrap_form_for(@profile, layout: :horizontal, html: {id: "profile-form"}) do |f| %>
<%= f.text_field :name %>
<%= f.text_field :number, id: "number-field" %> //Field to check
<%= form_group do %>
<%= f.primary %>
<% end %>
<% end %>
应用程序/资产/ JavaScript的/ profile_number_control.coffee:
$(document).on 'ready page:load', ->
$field = $("#number-field")
$group = document.getElementById("profile-form").childNodes[5]
numberPattern = "^(19|20)[0-9]{6}-[0-9]{4}$"
$helpBlock = $group.getElementsByClassName("help-block")[0]
$field.keyup ->
//This works fine, just wanted to show what is going on
if inputIsValid()
set $group class to " has-success"
set $helpBlock message to successful
else
set $group class to " has-error"
set $helpBlock message to corresponding error message
这是问题所在。我希望这个脚本适用于profile#new和profile#edit,但是由于document.getElementById("profile-form").childNodes
给出的元素数组根据当前视图的不同而不同,所以我不能在#new中使用相同的索引(在本例中为5)和#update。
有谁知道如何在我的视图中为该特定的form_group设置一个ID?或者是否必须实际写出整个html代码才能正确放置id?
检查了这一点,这可能帮助http://stackoverflow.com/questions/12202142/manually-set-the-ids-of-form-input-fields-in-a -simpleform- –
根据[docs](https://github.com/bootstrap-ruby/rails-bootstrap-forms)使用包装找到解决方案。这不允许添加一个ID,但你可以添加一个类。所以我用一个唯一命名的类做了一个解决方法。 – Ozgar