There are times when you need to process the selected text from long text inside a text area or a text box. This can be easily implemented in JavaScript. The starting index and ending index of the selection can be obtained using "selectionStart" and "selectionEnd". The JavaScript function implementation using this is shown in this post.
The function will get the text from the textarea with id "text", then separates the selection and display it using JavaScript alert. The function is triggered by the onclick event of the button.
The statement document.getElementById("text") gets the access to the required textarea. This is stored in variable text. Now the starting index of selection can be obtained by the statement text.selectionStart and the ending index can be obtained by the statement text.selectionEnd. The statement text.value gives the entire content of the textarea. Now the substr() function is used to extract the selected text. The two arguments for substr() function are the starting index and the length. The length can be found by subtracting starting index from ending index. The result is stored in a variable t, which is displayed using alert() function.
The function will get the text from the textarea with id "text", then separates the selection and display it using JavaScript alert. The function is triggered by the onclick event of the button.
<HTML> <HEAD><TITLE>Selection</TITLE> <SCRIPT type="text/javascript"> function disp() { var text = document.getElementById("text"); var t = text.value.substr(text.selectionStart,text.selectionEnd-text.selectionStart); alert(t); } </SCRIPT> </HEAD> <BODY> <TEXTAREA id="text">Hello, How are You?</TEXTAREA><BR> <INPUT type="button" onclick="disp()" value="Select text and click here" /> </BODY> </HTML>
The statement document.getElementById("text") gets the access to the required textarea. This is stored in variable text. Now the starting index of selection can be obtained by the statement text.selectionStart and the ending index can be obtained by the statement text.selectionEnd. The statement text.value gives the entire content of the textarea. Now the substr() function is used to extract the selected text. The two arguments for substr() function are the starting index and the length. The length can be found by subtracting starting index from ending index. The result is stored in a variable t, which is displayed using alert() function.
No comments:
Post a Comment