Insert Text/String at Cursor Position inside Textbox/TextArea Using Javascript
The following trick can be used to insert Random text wherever the blinking cursor is present on the click of Button..
<html> <head> <script> function getCaret(el) { if (el.selectionStart) { return el.selectionStart; } else if (document.selection) { el.focus(); var r = document.selection.createRange(); if (r == null) { return 0; } var re = el.createTextRange(), rc = re.duplicate(); re.moveToBookmark(r.getBookmark()); rc.setEndPoint('EndToStart', re); return rc.text.length; } return 0; } function InsertText() { var textarea = document.getElementById('txtArea'); var currentPos = getCaret(textarea); //alert(currentPos); var strLeft = textarea.value.substring(0, currentPos); var strMiddle = "-- Hello World --"; var strRight = textarea.value.substring(currentPos, textarea.value.length); textarea.value = strLeft + strMiddle + strRight; } </script> <title>Insert Text @ Cursor Position</title></head> <body> <textarea id="txtArea" >Lorem ipsum dolor sit amet, consectetur adipiscing elit.</textarea> <button onclick="InsertText();">Insert Text</button> </body> </html>
Thanks I hope ths will work
ReplyDelete