Text fields

Fields created by <input> tags with a type of text or password, as well as textarea tags, share a common interface.

Their DOM elements have a value property that holds their current content as a string value. Setting this property to another string changes the field's content.

The selectionStart and selectionEnd properties of text fields give us information about the cursor and selection in the text. When nothing is selected, these two properties hold the same number, indicating the position of the cursor. For example, 0 indicates the start of the text, and 20 indicates the cursor is after the 20th character.

The following code wires up a <textarea> tag with an event handler that, when you press F2, inserts the string “Khasekhemwy” for you.


var textarea = document.querySelector("textarea");
textarea.addEventListener("keydown", function(event) {
    //The keycode for F2 happens to be 113
    if (event.keyCode == 113) {
        replaceSelection(textarea, "Khasekhemwy");
function replaceSelection(field, word) {
    var from = field.selectionStart,
        to = field.selectionEnd;
    field.value = field.value.slice(0, from) + word +
    //Put the cursor after the word
    field.selectionStart = field.selectionEnd =
        from + word.length;

The replaceSelection function replaces the currently selected part of a text field's content with the given word and then moves the cursor after that word so that the user can continue typing.

The "change" event for a text field does not fire every time something is typed. Rather, it fires when the field loses focus after its content was changed.

The following example shows a text field and a counter showing the current length of the text entered.

<input type="text">length:<span id="length">0</span>

var text = document.querySelector("input");
var output = document.querySelector("#length");
text.addEventListener("input", function() {
    output.textContent = text.value.length;
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +