0

I have a text box.

<input type="text" name="FirstName" value="Mickey">

I want the user to prevent from entering empty space or tab or new line.Spaces between characters is allowed. How can I do that? Can some one give me a working demo? I have this now

JavaBeginner
  • 105
  • 3
  • 12

6 Answers6

1

Try this one, spaces are allowed after if not the start of the string

window.onload = function () {
var inputEl = document.getElementById("nospace");
inputEl.addEventListener("keydown", function (e) {
    if (e.keyCode == 32 && this.value.length==0) {
        e.preventDefault();
    }
  });
}
http://jsfiddle.net/k6She/
Gena Moroz
  • 929
  • 5
  • 9
1

Just add one more condition like

if (inputEl.value.length == 0) {
            if (e.keyCode == 32) {
                e.preventDefault();
            }
        }

FYI: You can't have new line in TextBox, so no need to prevent enter key

window.onload = function () {
    var inputEl = document.getElementById("nospace");
    inputEl.addEventListener("keydown", function (e) {
        if (inputEl.value.length == 0) {
            if (e.keyCode == 32) {
                e.preventDefault();
            }
        }
    });
}

Check this JSFiddle

Praveen
  • 55,303
  • 33
  • 133
  • 164
0

Try this

$(document).ready(function(){
             $("#target").keypress(function(e) {
               if(e.keyCode == 13 || e.keyCode==32)
                   return false;

});
 });
Indra Yadav
  • 600
  • 5
  • 22
0

Here I am checking the keycode of space bar and tab.Normally new line is not allowed in input type="text".

 window.onload = function () {
        var inputEl = document.getElementById("nospace");
        inputEl.addEventListener("keydown", function (e) {
            if (e.keyCode == 32 || e.keyCode == 9) {
                e.preventDefault();
            }
        });
    }

JSFIDDLE

EDIT: Try this: Sample Code

 $("#nospace").keydown(function (e) {
        if (e.keyCode == 32 || e.keyCode==9) {
            e.preventDefault();
        }
    });
Saritha.S.R
  • 800
  • 1
  • 6
  • 19
0

working sample

HTML

<input>

Javascript

$("input").on("keydown", function (e) {
    return e.which !== 32;
});

This will allow all alphabets,letters,special characters except whitespace..

Sasidharan
  • 3,676
  • 3
  • 19
  • 37
0

Fiddle: http://jsfiddle.net/Rs6Gx/

Js:

$(function(){
    $("input").keyup(function(e){
         $(this).val($(this).val().replace(/^\s/g, ""));
    });
});
Avin Varghese
  • 4,340
  • 1
  • 22
  • 31