2016-03-02 17 views
0

我有一個下拉列表,其中有其他選項,當選擇其他選項時出現一個新的字段,我們可以輸入文本指定其他,BUt文本填充時我沒有得到填補了該領域的數據我只得到其他在下拉字段中插入的文本沒有反映

HTML:

<html> 
<head> 
    <script type="text/javascript"> 
    function showfield(name){ 
    if(name=='Other')document.getElementById('div1').innerHTML='Other: <input type="text" name="other" />'; 
    else document.getElementById('div1').innerHTML=''; 
    } 
    </script> 
</head> 
<body> 
    <select name="drop" id="drop" onchange="showfield(this.options[this.selectedIndex].value)"> 
    <option selected="selected">Please select ...</option> 
    <option value="car">car</option> 
    <option value="bike">bike</option> 
    <option value="Other">Other</option> 
    </select> 
    <div id="div1"></div> 
</body> 
</html> 

而如何把一個幫助文本,當我們插入時,另一個是即將到來的新的文本框裏面的數據將消失選擇。

在此先感謝。

+0

使用jQuery是這樣的事情更容易爲工作 – RRR

回答

0

由於您使用的innerHTML,以前輸入的值將被清除,以避免這種情況,可以追加輸入元素如下:

var input = document.createElement('input'); 
input.type = "text"; 
input.name="other" 
document.getElelmentById('div1').appendChild(input); 
1

從選擇標籤移除onchange事件。

var select = document.getElementById('drop'); 

select.addEventListener("change", processEvent, false); 

function processEvent() { 
    var name = this.value; 
    if(name == 'Other') { 
    document.getElementById('div1').innerHTML='Other: <input type="text" name="other" />'; 
    } else { 
    document.getElementById('div1').innerHTML= name; 
    } 
} 
+0

這應與JS代碼來代替? – user5358888

+0

是替換你的js代碼。 – cheralathan

3

試試這個它你

<html> 
<head> 
    <script type="text/javascript"> 
    function showfield(name){ 
    var name=document.getElementById("drop").value; 
    if(name=='Other'){ 
      document.getElementById('div1').innerHTML='Other: <input type="text" name="other" />'; 
     } 
     else { 
       document.getElementById('div1').innerHTML=''; 
     } 
    } 
    </script> 
</head> 
<body> 
    <select name="drop" id="drop" onchange="showfield()"> 
    <option selected="selected">Please select ...</option> 
    <option value="car">car</option> 
    <option value="bike">bike</option> 
    <option value="Other">Other</option> 
    </select> 
    <div id="div1"></div> 
</body> 
</html> 
+0

當我打印或插入數據庫時​​,我回顯我只看到「其他」,但沒有在文本字段中鍵入的值..請幫助 – user5358888

+0

代碼爲您工作,當你選擇其他選項,在下拉顯示輸入字段 –