Language: HTML | XAML

Quickstart: Text input and editing(HTML)

Applies to Windows and Windows Phone

Windows Store apps using JavaScript can use several elements for entering and editing text, along with a set of attributes and properties for formatting text. The primary text-entry elements are text box, text area, password input box, and rich edit box/rich text box. This quickstart shows you how you can use these elements to display, enter, and edit text.

See this feature in action as part of our App features, start to finish series:  Windows Store app UI, start to finish

Prerequisites

Choosing a text control

Windows Store apps using JavaScript can use 4 primary text-entry elements: text box, text area, password input box, and rich edit box/rich text box. The element that you use depends on your scenario. Here are some scenarios and the recommended elements.

ScenarioRecommended elements

Enter or edit plain text, such as in a form.

Text box, text area

Enter a password.

Password input box

Edit a document, article, or blog that requires formatting, paragraphs, hyperlinks, or inline images.

Rich edit box/rich text box

 

Note  Secondary text-entry elements are available, but they are outside of the scope of this topic. These elements include email input box, number input box, and URL input box.

Text box and text area

You can use text box and text area elements to enter and edit unformatted text. You use the text box for a single line of text and a text area for multiple lines of text. Here's the HTML for a simple text box.


<input type="text" />

Here's the HTML for a simple text area.


<textarea></textarea>

You can make a text box or text area read-only by setting its readonly property to readonly. You can get or set the selected text in a text area using the selectionStart and selectionEnd properties. Use the onselect event to do something when the user selects text.

Here, we have an example of these properties and events in use. When you select text in the first text area, the selected text is displayed in the second text area, which is read-only. The values of the selection length and selectionStart properties are shown in two label elements. This is done using the onselect event.



<!-- default.html -->

<!-- ... -->
<div><textarea id="textarea" rows="3">The text that is selected in this text area will show up in the read-only text area below.</textarea></div>
<div><textarea id="readonlyTextarea" contenteditable="false"></textarea></div>
<div><label id="selLength"></label></div>
<div><label id="selStart"></label></div>
<!-- ... -->




// default.js

(function () {
    // ...

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: ...
            } else {
                // TODO: ...
            }
            args.setPromise(WinJS.UI.processAll().done(
                function () {
                    var textArea = document.getElementById("textarea");
                    textArea.addEventListener("select", onselectTextarea, false);

                    // ...
                }
            ));
         }
    };

    app.oncheckpoint = function (args) {
        // TODO: ...
    };

    function onselectTextarea() {
        var textarea = document.getElementById("textarea");
        var readonlyTextarea = document.getElementById("readonlyTextarea");
        var selLength = document.getElementById("selLength");
        var selStart = document.getElementById("selStart");

        readonlyTextarea.value = textarea.value.substring(
                                 textarea.selectionStart,
                                 textarea.selectionEnd);
        selLength.innerText = "Selection length is " +
                              (textarea.selectionEnd -
                              textarea.selectionStart);
        selStart.innerText = "Selection starts at " + textarea.selectionStart;
    }

    // ...

    app.start();
})();

Here's the result of this code.

Selected text in a text box.

Password input box

You can enter a single line of non-wrapping content in a password input box element. The user cannot view the entered text by default; only password characters that represents the text are displayed.

You get the text that the user entered from the value property, typically in the handler for the onchange event.

Here's the code that shows a password input box in use. When the user enters a password, it is checked to see if it is the literal value "Password" or if it is shorter or longer than 8 characters. If it is, we display a message to the user in a label element.


<!-- default.html -->

<!-- ... -->
<div><input id="password" type="password" placeholder="Enter 8 characters"/></div>
<div><label id="status"></label></div>
<!-- ... -->



// default.js

(function () {
    // ...

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: ...
            } else {
                // TODO: ...
            }
            args.setPromise(WinJS.UI.processAll().done(
                function () {
                    //...

                    var password = document.getElementById("password");
                    password.addEventListener("change", onchangePassword, false);

                    // ...
                }
            ));
         }
    };

    app.oncheckpoint = function (args) {
        // TODO: ...
    };

    // ...

    function onchangePassword() {
        var password = document.getElementById("password");
        var status = document.getElementById("status");

        if (password.value == "Password") {
            status.innerText = "'Password' is not allowed as a password.";
        }
        else if (password.value.length != 8) {
            status.innerText = "Password must be exactly 8 characters.";
        }
        else {
            status.innerText = "";
        }
    }

    // ...

    app.start();
})();


Rich edit box/rich text box

You can use a rich edit box/rich text box element to enter and edit rich text documents that contain formatted text, hyperlinks, and images. You can make a rich edit box/rich text box read-only by setting its contentEditable property to false.

You can use properties such as innerHTML to get a rich edit box/rich text box element's content.

This example shows how to load and save HTML content in a rich edit box/rich text box.



<!-- default.html -->

<!-- ... -->
<div>
    <button id="openFile">Open file</button>
    <button id="saveFile">Save file</button>
</div>
<div id="editor" contenteditable="true" />
<!-- ... -->


// default.js

(function () {
    // ...

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: ...
            } else {
                // TODO: ...
            }
            args.setPromise(WinJS.UI.processAll().done(
                function () {
                    //...

                    var openFile = document.getElementById("openFile");
                    openFile.addEventListener("click", onclickOpen, false);

                    var saveFile = document.getElementById("saveFile");
                    saveFile.addEventListener("click", onclickSave, false);

                    // ...
                }
            ));
         }
    };

    app.oncheckpoint = function (args) {
        // TODO: ...
    };

    // ...
    
    function onclickOpen() {
        var openPicker = new Windows.Storage.Pickers.FileOpenPicker();

        openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.documentsLibrary;
        openPicker.fileTypeFilter.replaceAll([".html"]);
        openPicker.pickSingleFileAsync().then(
            function (file) {
                if (file) {
                    Windows.Storage.FileIO.readTextAsync(file).then(
                        function (fileContent) {
                            var editor = document.getElementById("editor");
                            editor.innerHTML = fileContent;
                        }
                    );
                }
            }
        ); 
    }

    function onclickSave() {
        var savePicker = new Windows.Storage.Pickers.FileSavePicker();

        savePicker.suggestedStartLocation =
            Windows.Storage.Pickers.PickerLocationId.documentsLibrary;
        savePicker.fileTypeChoices.insert("HTML", [".html"]);
        savePicker.suggestedFileName = "Sample HTML Markup";
        savePicker.pickSaveFileAsync().then(
            function (file) {
                if (file) {
                    var fileContents = document.getElementById("editor").innerHTML;
                    // Prevent updates to the remote version of the file until 
                    // completeUpdatesAsync is called.
                    Windows.Storage.CachedFileManager.deferUpdates(file);
                    Windows.Storage.FileIO.writeTextAsync(file, fileContents).done(
                        Windows.Storage.CachedFileManager.completeUpdatesAsync(file).done()        
                    );
                }
            }
        );
    }

    app.start();
})();

Using the touch keyboard

Windows 8 has a touch keyboard for text entry when an app runs on a device with a touch screen. The touch keyboard is invoked when the user taps on an editable input element, such as a text box or password input box, and is dismissed when the input field loses focus. The touch keyboard uses accessibility info to determine when it is invoked and dismissed. The layout of the touch keyboard may change based on the type of the editable input element. For example, for an email input box, the @ key will appear on the touch keyboard.

Summary and next steps

You learned how to create text box, text area, password input box, and rich edit box/rich text box elements to display and edit text in your app.

For more code examples that show these controls, see the HTML essential controls sample.

Related topics

Guidelines and checklist for text input

 

 

Show:
© 2014 Microsoft