In my current project, I have a textbox where the user will enter some numeric ID (like a product ID) — For example: 12345-123-1234567-12345.
I want to have a JavaScript in my aspx page that, when a user presses Ctrl+V to paste in text, will format that text irrespective of the text’s present format.
For example, if the text is in formatted like 12345---123-123456712345 then the function will format it to 12345-123-1234567-12345.
EDIT:
Tried your Suggetion but it’s not working. I tried like this way… below code sample
<asp:TextBox ID="TextBox1" runat="server" Text="" ></asp:TextBox>
<br />
<br />
<script language="JavaScript" type="text/javascript">
var tb = document.getElementById("TextBox1");
tb.OnTextChanged = function () {
this.value = this.value.replace("---", "-");
};
</script>
It’s erroring out saying
Microsoft JScript runtime error: Unable to set value of the property
‘OnTextChanged’: object is null or undefined
To update a textbox whenever its text is change, you can use the “onchange” event (just note that the change won’t happen until focus leaves the textbox)
First, give your textbox a unique id—asp.net version 4 has features that allow you to give form elements id’s that won’t be “messed with”—then set the onchange event.
EDIT
You can catch the
keyupevent, and check to see if the user has just hit control-v. If so, you can modify the textbox’s current value. Just note that this will not work if the user pastes by right clicking.The best way to handle this is with the onchange event, which will work no matter how the textbox is changed.
DEMO