JavaScript Tutorial JavaScript Examples JQuery Tutorial CSS Tutorial HTML Tutorial About Us

Lesson 16: onChange & onSelect events


16.1 The onChange Event

The onChange event occurs when the users alter the input into form elements, such as a text box. In the following example, we shall show you how this event triggers a pop-up message when the user enters something into a textbox and alter its content. The JavaScript is as follows:

<script>
function showMessage(){
window.alert("You Have Changed the Content");
</script>

You need to include this textbox on the web page using the following syntax:

<input type="text" name="textbox" size="50" onChange="showMessage()">

Enter some text in the text box and click once outside the textbox to see the effect.

When enters something into the textbox, alters it and then click outside the textbook, he will see a pop-up dialog then reads "You have changed the content"

16.2 The onSelect Event

The onSelect event occurs when the user selects text by dragging the mouse across a certain part of the text. We can write JavaScript code for this event. In Example 16.2, when the user types some characters into the text area and then select a part of the text, the selected will be shown to the user via a pop-up dialog.

Example 16.2

<script>

function SelText()
{
 yourtext = document.getElementById("selectedtext").value;
 alert("You text you have selected is: "+yourtext );
}
</script>

In addition, create a textarea and assign it an id, as follows:

 < textarea id="selectedtext"  rows="5" cols="20" onSelect="SelText()"></textarea>

Try it out by entering some text in the text area and select it

You will notice that the JavaScript above will show you the full text even though you only select a part of the text. Now, we shall improve on the above script by adding a few more lines as follows and modify the code a bit

var first = yourtext.selectionStart; // retrieve the index of the first selected character
var last = yourtext.selectionEnd;    // retrieve the index of the last selected character
var selectedTxt = yourtext.value.substring(first, last); // retrieve the selected text
alert("You text you have selected is: "+selectedTxt );  // show the selected text on the pop-up dialog

The full JavaScript is as follows:

<script>

function SelText()
{
var first = yourtext.selectionStart; // retrieve the index of the first selected character
var last = yourtext.selectionEnd;    // retrieve the index of the last selected character
var selectedTxt = yourtext.value.substring(first, last); // retrieve the selected text
alert("You text you have selected is: "+selectedTxt );  // show the selected text on the pop-up dialog
}
</script>

Try it out by entering some text in the text area and select a part of it


❮ Previous Lesson Next Lesson ❯


Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy