views:

342

answers:

3

I've got a textbox, and I want to select a substring programatically. Is there an easy way to do this?

+1  A: 

My JS is a little rusty, but something along the lines of:

document.getElementById("foo").value.substring(start, end);

should get you started.

And, I'm assuming that you're referring to a <textarea>.

Adrien
A: 
<input type="text" id="textbox" value="sometextintextbox" />

<script type="text/javascript">
var textboxvalue=document.getElementById("textbox").value;
alert(textboxvalue.substring(3,7));
</script>
Chris Tek
+5  A: 

To highlight the selected text in the textbox, you can use this javascript snippet:

var textbox = document.getElementById("mytextbox");
if (textbox.createTextRange) {
    var oRange = this.textbox.createTextRange(); 
    oRange.moveStart("character", start); 
    oRange.moveEnd("character", length - this.textbox.value.length); 
    oRange.select();
} else if (this.textbox.setSelectionRange) {
    textbox.setSelectionRange(start, length);
}

textbox.focus();

In this snippet, mytextbox is the id the input textbox and start and length represent your substring parameters.

Jose Basilio
Ugh...This was a pain to get working correctly in IE
maleki