dadamssg Posted August 9, 2009 Share Posted August 9, 2009 i found this snippet to insert text into a text box where the caret is currently textBox1.Text = textBox1.Text.Insert(textBox1.SelectionStart, "Test"); but i don't know where to put this to make it work? is it part of a javascript function? do i put part of it equal to an onclick event? Quote Link to comment Share on other sites More sharing options...
MadTechie Posted August 9, 2009 Share Posted August 9, 2009 Looking at the code I don't know, however try this <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <script type="text/javascript"> function insertAtCaret(obj, text) { if(document.selection) { obj.focus(); var orig = obj.value.replace(/\r\n/g, "\n"); var range = document.selection.createRange(); if(range.parentElement() != obj) { return false; } range.text = text; var actual = tmp = obj.value.replace(/\r\n/g, "\n"); for(var diff = 0; diff < orig.length; diff++) { if(orig.charAt(diff) != actual.charAt(diff)) break; } for(var index = 0, start = 0; tmp.match(text) && (tmp = tmp.replace(text, "")) && index <= diff; index = start + text.length ) { start = actual.indexOf(text, index); } } else if(obj.selectionStart) { var start = obj.selectionStart; var end = obj.selectionEnd; obj.value = obj.value.substr(0, start) + text + obj.value.substr(end, obj.value.length); } if(start != null) { setCaretTo(obj, start + text.length); } else { obj.value += text; } } function setCaretTo(obj, pos) { if(obj.createTextRange) { var range = obj.createTextRange(); range.move('character', pos); range.select(); } else if(obj.selectionStart) { obj.focus(); obj.setSelectionRange(pos, pos); } } </script> </head> <body> <form name="form"> <input type="button" value="Insert text" onclick="insertAtCaret(this.form.text, this.form.string.value)"> <input type="text" name="string"><br /> <textarea name="text" cols="60" rows="10"></textarea> </form> </body> </html> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.