Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I want to avoid more than one blank space while typing in textbox. single blank space is allowed between words.
Thanks in advance
Posted

I used this to achieve the required

here 'description' is the id of the input html element

JavaScript
$('#description').keypress(function (e) {
               if (e.charCode == 32 && $(this).val()[$(this).val().length - 1] == ' ')
                   e.preventDefault();
           });
 
Share this answer
 
v2
Hello,

You can do this either using JavaScript or Server side PHP. I am presenting here the JavaScript version. I am assuming that your textbox name is txtNotes & is declared as shown below.
HTML
<input type="text id="txtNotes" name="txtNotes" onChange="removeSpaces(this)"/>

The Javascript
JavaScript
function removeSpaces(ctrl)
{
    var ret = "";
    if (ctrl.value != null && ctrl.value.length > 0) {
        var parts = ctrl.value.split(" ");
        for (var i = 0; i < parts.length; i++) {
            var tmp = parts[i].replace(/^\s+|\s+$/g,'');
            if (tmp.length > 0) {
                ret += (tmp + " ");
            }
        }
        ctrl.value = ret.substring(0, ret.length - 1);
    }
}
 
Share this answer
 
v2
Comments
Graham Breach 12-Apr-13 7:55am    
Not only would that not work, it adds an extra space at the end.
Prasad Khandekar 12-Apr-13 11:02am    
Thank's Graham,

Updated the code.
You could do it with a regular expression, either in Javascript or PHP:

Javascript version:
JavaScript
function removeSpaces(ctrl)
{
  var s = ctrl.value;
  ctrl.value = s.replace(/\s+/g, ' ');
}
 
Share this answer
 
Comments
Prasad Khandekar 12-Apr-13 11:05am    
Tried it, It won't remove trailing spaces from input.
Graham Breach 12-Apr-13 11:11am    
The OP didn't ask for removing trailing spaces, only for replacing double spaces with single.

But if you need that: ctrl.value = s.replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '');
Prasad Khandekar 12-Apr-13 11:15am    
My +5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900