2013-10-09 70 views
-3

我對JavaScript並不熟悉,但需要解決一個相當簡單的問題。使用javascript將textarea分割成不同的文本框

我希望能夠在html textarea中輸入信息,按下按鈕並將textarea的內容分割成不同的文本框。也許可視化會更清楚:

所以我想從這個去:

<textarea> 
Line 1 
Line 2 
Line 3 
<textarea> 

要這樣:

<input type="text" value="Line 1" /> 
<input type="text" value="Line 2" /> 
<input type="text" value="Line 3" /> 

謝謝!

+3

的內容創建輸入元素和你嘗試過什麼? – putvande

回答

3

假設你的HTML如下:

<textarea id="text_area"> 
Line 1 
Line 2 
Line 3 
</textarea> 

<div id="input_text"></div> 

這個Javascript會根據你的文本區域

// Destination element to contain the input elements 
var destination = document.getElementById('input_text'); 

// Contents of textarea 
var content = document.getElementById('text_area').innerHTML; 

// Array containing each line of the textarea 
var lines = content.split('\n'); 

for(i = 0; i <= lines.length; i++) 
{ 
    if(lines[i] != '' && lines[i] != undefined) 
    { 
     // Create input element 
     el_name = 'input_' + i; 
     el = document.createElement('input'); 
     el.setAttribute('type', 'text'); 
     el.setAttribute('name', el_name); 
     el.setAttribute('value', lines[i]); 

     // Append input element to destination 
     destination.appendChild(el); 
    } 
} 

在這裏工作例如http://fiddle.jshell.net/AvA3a/

相關問題