2016-02-20 55 views
0

我有不同的基本索引頁與下拉是/沒有選擇。默認爲No. 選擇是時,我想顯示文本輸入標籤,以便輸入跳過評估的原因。 如果選擇否,則應刪除文本輸入字段。Rails - text_field_tag不顯示與Javascript

這裏是我的代碼:

<h1 id='main_header'>test-01</h1> 

<table> 
    <thead> 
    <th>Action<//th> 
    <th>Skip assessment</th> 
    <th>Reason for skipping</th> 
    </thead> 
    <tbody> 
    <tr> 
     <td> 
     <%= link_to 'Start asseement', controller: :home, action: :start_assessment, id: 'start_assessment' %> 
     </td> 
     <td> 
     <%= select_tag "skip_option", options_for_select([ "Yes", "No" ], "No"), id: "skip_option", :onchange => "reason_picker()" %> 
     </td> 
     <td> 
     <%= text_field_tag "reason_for_skipping", nil, size: 50, placeholder: 'Enter reason here...', style: "display: none;" %> 
     </td> 
    </tr> 
    </tbody> 
</table> 

<script> 
    $(document).ready (
    function reason_picker() { 
     var selected = document.getElementById("skip_option").selectedIndex; 
     alert(selected); 
     if (selected == 0) { 
     $("#reason_for_skipping").show(); 
     alert("if"); 
     } 
     else { 
     $("#reason_for_skipping").hide(); 
     alert("else"); 
     } 
    } 
); 
</script> 

我總是得到「其他」分支,選擇指數始終爲1,並從下拉選擇是下來的時候(這應該是選擇指數0),文本輸入標籤從不顯示。 不知道如何解決這個問題。

回答

1

的問題是在這條線

<%= select_tag "skip_option", options_for_select([ "Yes", "No" ], "No"), id: "skip_option", :onchange => "reason_picker()" %> 

reason_picker()將不確定

要解決它,你可以很容易地重構你的JavaScript是這樣的:

<script> 
    $(document).ready (
    window.reason_picker = funtion() { # <-- change here 
     var selected = document.getElementById("skip_option").selectedIndex; 
     alert(selected); 
     if (selected == 0) { 
     $("#reason_for_skipping").show(); 
     alert("if"); 
     } 
     else { 
     $("#reason_for_skipping").hide(); 
     alert("else"); 
     } 
    } 
); 
</script> 
+0

完美地工作! –

+0

當顯示reason_for_skipping時,有沒有辦法隱藏link_to,反之亦然? –

+0

你可以用javascript來做,對不對? –