2016-07-14 119 views
0

我想執行一個檢查,以便使用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?

+0

檢查了這一點,這可能幫助http://stackoverflow.com/questions/12202142/manually-set-the-ids-of-form-input-fields-in-a -simpleform- –

+0

根據[docs](https://github.com/bootstrap-ruby/rails-bootstrap-forms)使用包裝找到解決方案。這不允許添加一個ID,但你可以添加一個類。所以我用一個唯一命名的類做了一個解決方法。 – Ozgar

回答

0

這可能有幫助!

<%= bootstrap_form_for(@profile, layout: :horizontal, html: {id: "profile-form"}) do |f| %> 
 
    <%= f.text_field :name %> 
 
    <%= f.text_field :number, :input_html => { id: "number-field" } %> //Field to check 
 
    <%= form_group do %> 
 
     <%= f.primary %> 
 
    <% end %> 
 
<% end %>

+0

如果我使用simple_form,我可能會工作。如果我沒有找到其他解決方案,我會繼續嘗試,也許切換。感謝您的回答:) – Ozgar

+0

那麼如果您使用的是Rails 4,爲什麼要使用引導形式?爲什麼不使用Rails給你的第一個地方? –

+0

我實際上使用了nested_bootstrap_form,並且「給你第一個地方?」你的意思是腳手架?因爲如果是這樣我更願意寫我自己的代碼,腳手架往往會讓代碼膨脹一點。 – Ozgar