2

There is a nice solution to accomplish what I am after here, where they use this javascript function:

var text = document.getElementById('txtText');
text.addEventListener('input', function(e){
  var keyCode = e.keyCode ? e.keyCode : e.which;
  this.value = this.value.replace(/\s/g, '')
  if(keyCode === 32) return;
})

which is applied to the following element:

<input type='text' id="txtText">

In my case, I don't have an <input... element, but an <asp:TextBox element, and the function above isn't working. I am using the correct element ID but I can still paste and also type white spaces. What am I missing?

1

2 Answers 2

2

I would use a Class name and bind the script to the elemens with that class. Then you don't need ClientID and it works for multiple elements.

<asp:TextBox ID="TextBox1" runat="server" CssClass="NoSpaces"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server" CssClass="NoSpaces"></asp:TextBox>

<script>
    $('.NoSpaces').bind('keyup blur', function (e) {
        var keyCode = e.keyCode ? e.keyCode : e.which;
        this.value = this.value.replace(/\s/g, '')
        if (keyCode === 32) return;
    });
</script>

If you do want to use ClientID, then do this

$('#<%= TextBox1.ClientID %>').bind('keyup blur', function (e) {

However if the input is not an aspnet control (asp:TextBox or input with runat=server) then it wont work. Another issue with ClientID is that the script needs to be inline on the page containing that control.

Sign up to request clarification or add additional context in comments.

2 Comments

This worked! Still can't get my head around why the solution with '<%= txtText.ClientID%>' isn't working...
I've added more examples.
2

It seems you don't select Textbox item properly.

You can get the control ID for HTML markup that is generated by ASP.NET by using ClientID as following:

var text = document.getElementById('<%= txtText.ClientID%>');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.