2016-11-13 170 views
2

我想新的生產線在JavaScript中添加新的行字符的文本框,更新文本框的值使用下面的代碼:集光標位置的JavaScript

ele.value = ele.value + "\n"; 

ele.focus(); 

// To update cursor position to recently added character in textBox 
ele.setSelectionRange(value.length, value.length); 

上面的代碼更新,文本框的值,但不更新光標位置到新線。

(雖然它更新光標位置,當我點擊文本框的外面,然後再次單擊內部文本框而不是在textBox中已經被用戶編輯。)

+0

哪個瀏覽器?我的答案如預期的那樣在Chrome中運行,但不是Safari瀏覽器。 – skav

回答

4

這應該工作在Firefox還有:

HTML:

<!DOCTYPE html> 
    <html> 
    <head> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width"> 
    </head> 
    <body> 
    <textarea id="myText" rows="4" cols="50" onkeypress="">The rain in Spain falls mainly on the plains.</textarea> 
    <br> 
    <button onclick="updateText()">Update</button> 
    </body> 
</html> 

的Javascript:

function updateText(e) { 
var ele = document.getElementById('myText'); 
var newVal = 'Old McDonald had a farm.\n'; 

ele.value = newVal; 
ele.focus(); 

// To update cursor position to recently added character in textBox 
ele.setSelectionRange(newVal.length, newVal.length); 
} 

JS Bin example

我對焦後選擇文本。

2

function insertNewlineAndFocus() { 
 
    let textarea = document.getElementById("unicorn"); 
 
    textarea.value = textarea.value + "\n"; 
 
    textarea.setSelectionRange(textarea.value.length, textarea.value.length); 
 
    textarea.focus(); 
 
}
button { 
 
    display: block; 
 
    margin: 10px; 
 
} 
 
textarea { 
 
    min-width: 50%; 
 
    min-height: 100px; 
 
    margin: 10px; 
 
}
<button onclick="insertNewlineAndFocus()">do it!</button> 
 
<textarea id="unicorn">the most phenomenal text, really, its the best</textarea>