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?

Zizzipupp
  • 1,301
  • 1
  • 11
  • 27
  • Does this answer your question? [Getting Textbox value in Javascript](https://stackoverflow.com/questions/5039544/getting-textbox-value-in-javascript) – Heretic Monkey Nov 27 '19 at 18:25

2 Answers2

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%>');
Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28
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.

VDWWD
  • 35,079
  • 22
  • 62
  • 79