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
2009-07-14 18:08:13
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
2009-07-14 18:09:32
+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
2009-07-14 18:15:16
Ugh...This was a pain to get working correctly in IE
maleki
2009-07-14 20:26:14