Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CRTL+V (Paste) function automatic formatting in JavaScript asp.net

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

like image 700
Rahul Avatar asked Jun 25 '26 06:06

Rahul


1 Answers

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.

var tb = document.getElementById("textBoxId");
tb.onchange = function() {
   //I think you want:
   this.value = this.value.replace("---", "-");
};

EDIT

You can catch the keyup event, 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.

   document.getElementById("tb").onkeyup = function (e) {
       var key = e.which || e.keyCode;
       if (e.which === 86 && e.ctrlKey)
           alert("you pasted " + this.value);
   }; 

DEMO

like image 68
Adam Rackis Avatar answered Jun 26 '26 21:06

Adam Rackis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!