Lesson 16: onChange & onSelect Events

Learn how to handle user input changes and text selections with interactive examples.

16.1 Understanding onChange Event

The onChange event occurs when the value of a form element has been changed and the element loses focus. This event is commonly used with input fields, select dropdowns, and text areas.

Key points: The onChange event triggers only when the element loses focus after its value has changed. It does not fire on every keystroke.
User Input
Value Changed
Element Loses Focus
onChange Triggers

16.1.1 Basic onChange Example

Example 16.1: Input Field Change Detection

This example shows how onChange triggers when an input field is modified and then loses focus.

// JavaScript function
function handleChange() {
    const inputValue = document.getElementById("textInput").value;
    document.getElementById("changeResult").innerHTML = 
        `Input changed to: ${inputValue}`;
}

// HTML
<input type="text" id="textInput" onchange="handleChange()" 
       placeholder="Type and then click outside">
<div id="changeResult">Change result will appear here</div>
Change result will appear here

16.1.2 Select Dropdown onChange

Example 16.2: Dynamic Theme Changer

This example uses onChange with a select dropdown to change the page theme.

// JavaScript function
function changeTheme() {
    const theme = document.getElementById("themeSelect").value;
    document.body.className = theme;
    document.getElementById("themeResult").innerHTML = 
        `Current theme: ${theme}`;
}

// HTML
<select id="themeSelect" onchange="changeTheme()">
    <option value="">Select a theme</option>
    <option value="light-theme">Light Theme</option>
    <option value="dark-theme">Dark Theme</option>
    <option value="blue-theme">Blue Theme</option>
</select>
<div id="themeResult">Theme selection will appear here</div>
Theme selection will appear here

16.2 Understanding onSelect Event

The onSelect event occurs when a user selects text within an input field or textarea. This event is useful for creating text editors or when you need to know what text the user has selected.

Key points: The onSelect event triggers when text is selected, but note that it doesn't provide the selected text directly. We need to use additional methods to get the selected content.

16.2.1 Basic onSelect Example

Example 16.3: Text Selection Detection

This example shows how onSelect triggers when text is selected in an input field.

// JavaScript function
function handleSelect() {
    document.getElementById("selectLog").innerHTML += 
        "Text selected in the input field!\n";
}

// HTML
<input type="text" id="selectInput" onselect="handleSelect()" 
       value="Select some text in this field">
<div class="event-log" id="selectLog"></div>

16.2.2 Getting Selected Text

Example 16.4: Retrieving Selected Content

This example shows how to get the actual selected text using JavaScript.

// JavaScript function
function getSelectedText() {
    const inputField = document.getElementById("textField");
    const start = inputField.selectionStart;
    const end = inputField.selectionEnd;
    const selectedText = inputField.value.substring(start, end);
    
    if (selectedText) {
        document.getElementById("selectedTextResult").innerHTML = 
            `Selected text: ${selectedText}`;
    } else {
        document.getElementById("selectedTextResult").innerHTML = 
            "No text selected";
    }
}

// HTML
<textarea id="textField" rows="4" 
          onselect="getSelectedText()">
This is some sample text. Try selecting part of this text.
</textarea>
<div id="selectedTextResult">Selected text will appear here</div>
Selected text will appear here

16.3 Real-World Applications

These events are essential in many web applications. Here are practical examples:

16.3.1 Form Validation with onChange

Example 16.5: Real-time Email Validation

This example uses onChange to validate an email address as the user types.

// JavaScript function
function validateEmail() {
    const emailInput = document.getElementById("emailInput");
    const email = emailInput.value;
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const resultElement = document.getElementById("emailResult");
    
    if (emailRegex.test(email)) {
        resultElement.innerHTML = "✓ Valid email address";
        resultElement.style.color = "green";
        emailInput.style.borderColor = "green";
    } else {
        resultElement.innerHTML = "✗ Invalid email format";
        resultElement.style.color = "red";
        emailInput.style.borderColor = "red";
    }
}

// HTML
<input type="email" id="emailInput" onchange="validateEmail()" 
       placeholder="Enter your email">
<div id="emailResult">Validation result will appear here</div>
Validation result will appear here

16.3.2 Text Editor with onSelect

Example 16.6: Formatting Selected Text

This example demonstrates a simple text editor that formats selected text.

// JavaScript functions
function formatText(format) {
    const textarea = document.getElementById("editor");
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const selectedText = textarea.value.substring(start, end);
    
    if (!selectedText) return;
    
    let formattedText = "";
    switch(format) {
        case "bold":
            formattedText = `**${selectedText}**`;
            break;
        case "italic":
            formattedText = `*${selectedText}*`;
            break;
        case "underline":
            formattedText = `${selectedText}`;
            break;
    }
    
    const newText = textarea.value.substring(0, start) + 
                   formattedText + 
                   textarea.value.substring(end);
    
    textarea.value = newText;
    document.getElementById("formatResult").innerHTML = 
        `Formatted text: ${formattedText}`;
}

// HTML
<textarea id="editor" rows="6">
Select some text and click a formatting button.
</textarea>
<div class="demo-controls">
    <button onclick="formatText('bold')">Bold</button>
    <button onclick="formatText('italic')">Italic</button>
    <button onclick="formatText('underline')">Underline</button>
</div>
<div id="formatResult">Formatting result will appear here</div>
Formatting result will appear here