2016-11-05 84 views
0

恐怕我卡住了,我希望有一些社區智慧。如果在多個選擇輸入中選擇了「其他」,Javascript顯示/隱藏文本字段輸入

我正在構建一個提交數據到SQL數據庫的HTML表單。其中一個表單域是多選輸入域,用戶可以選擇正在執行的操作類型。數組然後以逗號分隔值的形式導出到SQL字段。

我遇到的問題是我還希望用戶能夠輸入自定義操作類型,如果它未包含在提供的列表中。理想情況下,這將涉及在多重選擇中選擇「其他」,並出現新的文本輸入字段。

到目前爲止,我只能讓文本輸入字段出現,如果用戶選擇了「其他」,沒有別的。如果用戶選擇了多個項目,其中一個是「其他」,我是否可以顯示該字段?

非常感謝

function showfield(episode_procedure){ 
 
      if(episode_procedure=='Other')document.getElementById('otherprocedure').innerHTML='Other: <input type="text" name="episode_otherprocedure" style="width: 450px;"/>'; 
 
      else document.getElementById('otherprocedure').innerHTML=''; 
 
     }

 
<select multiple="multiple" data-placeholder="Click to select..." size="7" name="episode_procedure[]" style="width: 450px;" onchange="showfield(this.options[this.selectedIndex].value)"></p> 
 
     <option value="anterior resection">anterior resection</option> 
 
     <option value="appendicectomy">appendicectomy</option> 
 
     <option value="Other">Other</option></select> 
 
     
 
     <div id="otherprocedure"></div>

+0

你的代碼工作。它創建輸入點擊與他人。然後你期待什麼呢? – prasanth

+0

@prasad,當您從'select'框中選擇多個項目時,代碼不起作用。你可以檢查我的答案,例如如何用jquery做到這一點。 – Dekel

回答

1

使用jQuery這是很容易得到所有值在多select標籤:

$(select).val() 

現在,你只需要檢查'Other'裏面存在:

$(select).val().indexOf('Other') > -1 

$('#s1').on('change', function() { 
 
    if ($(this).val().indexOf('Other') > -1) { 
 
    $('#otherprocedure').html('Other: <input type="text" name="episode_otherprocedure" style="width: 450px;"/>') 
 
    } else { 
 
    $('#otherprocedure').html(''); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select id="s1" multiple="multiple" data-placeholder="Click to select..." size="7" name="episode_procedure[]" style="width: 450px;"> 
 
<option value="anterior resection">anterior resection</option> 
 
<option value="appendicectomy">appendicectomy</option> 
 
<option value="Other">Other</option></select> 
 

 
<div id="otherprocedure"></div>

相關問題