简体   繁体   中英

Textbox should not to allow spaces in asp.net using javascript

Textbox should not allow the spaces in it. I have written a java script which is working..But it failed when space bar is pressed continuously. Please suggest. Code i used given below :

<script type="text/javascript" language="javascript">
function splitText() 
{
var fullNumber = $get('<%= tbFullNumber.TextBoxClientID %>').value;        
$get('<%= tbFullNumber.TextBoxClientID %>').value = fullNumber.replace(' ', '');
fullNumber = $get('<%= tbFullNumber.TextBoxClientID %>').value;
}

I'd re-design the scripts to have it replace all spaces at once when the control loses focus. Slap a "spaces will be removed" bold label beside the textbox and you're golden.

This way, it doesn't matter how the input is made (do users type? do they copy-paste? do they keep buttons pressed ? do they use on-screen keyboard ? do they ...).

AFAIK two events are attached to this, onfocusout (when the control is about to lose focus but hasn't yet) and onblur (when the control has lost focus). You can of course handle both.

Replacing all spaces in a string is easy:

theString = theStringreplace(/\s/ig,''); // '  b  l ah  ' = 'blah'

You don't need to do that much code to prevent this type of scenario ... have a look in this fiddle ... Do something like this ..

HTML

<input type="text" onkeypress="handleSpace(event)"  />

JavaScript

function handleSpace(event) 
{
  //handling ie and other browser keycode 
  var keyPressed= event.which || event.keyCode;

  //Handling whitespace
  //keycode of space is 32
  if(keyPressed==32)
  {
    event.preventDefault();
    event.stopPropagation();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM