0

I need to deny initial spaces on my input (which is not in a form), I have code like this:

<input id="customer-name" class="required no-spaces" minlength="3"  />

And this is my javascript function:

$(".no-spaces").on('keypress', function(e) {
     if (e.which == 32) {
         return false;
     }
});

But this doesn't allow spaces in any part of the input. How to do it just before any text?

Edit: The real is that I'm doing an autocomplete with the input and, If i allow initial spaces it will return all data.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Jhonatan Sandoval
  • 1,283
  • 6
  • 24
  • 40

4 Answers4

1

Verify if the string is empty beforehand.

$(".no-spaces").on('keypress', function(e) {
     if ($(this).val() == "" && e.which == 32) {
         return false;
     }
});

Also, check this in order to prevent the case where the user selects the entire text and then presses space and this to check if the cursor is indeed at the beggining of the input (Thanks to Barmar for mentioning this specific case)

Community
  • 1
  • 1
William Barbosa
  • 4,936
  • 2
  • 19
  • 37
1

Just simply check there is another character on textbox.

$(".no-spaces").on('keypress', function(e) {
     if (e.which == 32 && ($this).val() == '') {
         return false;
     }
});

Edit

I hope it might be work.

$(".no-spaces").on('keypress', function(e) {
     $(this).val(function(i, v) {
        if (v[0] == ' ') {
            return v.slice(1, v.length);
        };
        return v;
     });
});
Arkar Aung
  • 3,554
  • 1
  • 16
  • 25
  • Since this is the same as William Barbosa's answer, my comment there applies. – Barmar May 16 '14 at 16:17
  • I like your edit, but I think you'll still be able to copy/paste multiple spaces..I think you may want to make this recursively check `v[0]` and removing spaces until there isn't anymore. – Sam May 16 '14 at 16:52
0
$(".no-spaces").on('keypress', function(e) {
     if (e.which == 32) {
         $(this).val($(this).val().replace(/^\W*/, ''));
     }
});
Dan Smolinske
  • 319
  • 3
  • 7
0

This works for me.

$(".no-spaces").on('keypress', function(e) {
     var val = $(this).val();
     val_ltrim = ltrim(val);
     $(this).val(val_ltrim);
});

Greetings.

Jhonatan Sandoval
  • 1,283
  • 6
  • 24
  • 40