0

I have looked at many plugins for masking html inputs that seem to address concerns regarding numbers, such as amounts, dates, and identification numbers and have not yet seen any ready solutions for text fields. Suppose I have 'first' and 'last name' inputs that I automatically want to mask so that the format will show every word starting with an uppercase automatically.

john = Joen

Any suggestions?

user2917239
  • 898
  • 3
  • 12
  • 27

2 Answers2

3

You can try using onkeyup:

Demo

HTML:

<input id='first' onkeyup='mask("first");'>
<input id='last' onkeyup='mask("last");'>

JavaScript:

String.prototype.toTitleCase = function () {
    return this.replace(/\w\S*/g, function (txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
};

function mask(target) {
    var elem = document.getElementById(target);
    elem.value = elem.value.toTitleCase();
}
Vikram Deshmukh
  • 12,304
  • 4
  • 36
  • 38
1

Given the following HTML:

<input id="myText" type="text"/>

You can use JQuery's keyup function:

$("#myText").keyup(function(e) {
  var previousKey = this.value.substring(this.value.length-2,this.value.length-1);
  //check if previous key is a space, or for the first letter and if it is a valid letter
  if ((previousKey == " " || this.value.length == 1) && (e.which >= 65 && e.which <= 90)) {
      var newVal = this.value.substring(0, this.value.length-1);        
      this.value =newVal + String.fromCharCode(e.keyCode);
  }
});

See demo here

Fanie Reynders
  • 580
  • 3
  • 16