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

I used this to achieve the required

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

$('#description').keypress(function (e) {
               if (e.charCode == 32 && $(this).val()[$(this).val().length - 1] == ' ')
Share this answer

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.
<input type="text id="txtNotes" name="txtNotes" onChange="removeSpaces(this)"/>

The 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
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:
function removeSpaces(ctrl)
  var s = ctrl.value;
  ctrl.value = s.replace(/\s+/g, ' ');
Share this answer
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