7

JS Bin demo

This regex transform each lower case word to upper case. I have a full name input field. I do want the user to see that each word's first letter he/she pressed is converted to uppercase in the input field.

I have no idea how to properly replace the selected characters in the current input field.

$('input').on('keypress', function(event) {
  var $this = $(this),
      val = $this.val(),
      regex = /\b[a-z]/g;

  val = val.toLowerCase().replace(regex, function(letter) {
    return letter.toUpperCase();
  });

  // I want this value to be in the input field.
  console.log(val);
});
aegyed
  • 1,320
  • 3
  • 20
  • 39
  • 1
    You can use a css for the input element text-transform:capitalize; – Dineshkani Feb 04 '13 at 13:51
  • @Dineshkani It's worth noting this wouldn't be applied on form submission though, its only a style change. – Curtis Feb 04 '13 at 13:54
  • @Curt Thanks curt I learn this from you – Dineshkani Feb 04 '13 at 13:55
  • 1
    I usually do it [this way](http://jsfiddle.net/9zPTA/1/) ? – adeneo Feb 04 '13 at 13:59
  • 1
    Changing the value on `keypress` can get annoying for the user, because it keeps moving the cursor to the end of the box, even if they go back to change something. Consider doing it on `change` instead. – nbrooks Feb 04 '13 at 14:15
  • 1
    I updated the solution from adeneo to address @nbrooks concerns: http://jsfiddle.net/9zPTA/2/ using http://stackoverflow.com/a/14508837/1905055 - this is a clean real-time solution that lets the user know it's capitalized immediately, instead of onblur or something. – JSP64 Nov 08 '13 at 19:27
  • Duplicate Question : click on the below link for good answers .. http://stackoverflow.com/questions/1026069/capitalize-the-first-letter-of-string-in-javascript – Reetika May 06 '15 at 12:38
  • `onchange` is only triggered when the control is blurred. Try `onkeypress` instead. – Satbir Kira Nov 11 '15 at 09:12

8 Answers8

15

Given i.e: const str = "hello world" to become Hello world

const firstUpper = str.substr(0, 1).toUpperCase() + str.substr(1);

or:

const firstUpper = str.charAt(0).toUpperCase() + str.substr(1);

or:

const firstUpper = str[0] + str.substr(1);
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
8
input {
    text-transform: capitalize;
}

http://jsfiddle.net/yuMZq/1/

Using text-transform would be better.

dfsq
  • 191,768
  • 25
  • 236
  • 258
3

You can convert the first letter to Uppercase and still avoid the annoying problem of the cursor jumping to the beginning of the line, by checking the caret position and resetting the caret position. I do this on a form by defining a few functions, one for all Uppercase, one for Proper Case, one for only Initial Uppercase... Then two functions for the Caret Position, one that gets and one that sets:

function ProperCase(el) {
  pos = getInputSelection(el);
  s = $(el).val();
  s = s.toLowerCase().replace(/^(.)|\s(.)|'(.)/g, 
          function($1) { return $1.toUpperCase(); });
  $(el).val(s);
  setCaretPosition(el,pos.start);
}

function UpperCase(el) {
  pos = getInputSelection(el);
  s = $(el).val();
  s = s.toUpperCase();
  $(el).val(s);
  setCaretPosition(el,pos.start);
}

function initialCap(el) {
  pos = getInputSelection(el);
  s = $(el).val();
  s = s.substr(0, 1).toUpperCase() + s.substr(1);
  $(el).val(s);
  setCaretPosition(el,pos.start);
}

/* GETS CARET POSITION */
function getInputSelection(el) {
    var start = 0, end = 0, normalizedValue, range,
        textInputRange, len, endRange;

    if (typeof el.selectionStart == 'number' && typeof el.selectionEnd == 'number') {
        start = el.selectionStart;
        end = el.selectionEnd;
    } else {
        range = document.selection.createRange();

        if (range && range.parentElement() == el) {
            len = el.value.length;
            normalizedValue = el.value.replace(/\r\n/g, "\n");

            // Create a working TextRange that lives only in the input
            textInputRange = el.createTextRange();
            textInputRange.moveToBookmark(range.getBookmark());

            // Check if the start and end of the selection are at the very end
            // of the input, since moveStart/moveEnd doesn't return what we want
            // in those cases
            endRange = el.createTextRange();
            endRange.collapse(false);

            if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
                start = end = len;
            } else {
                start = -textInputRange.moveStart("character", -len);
                start += normalizedValue.slice(0, start).split("\n").length - 1;

                if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
                    end = len;
                } else {
                    end = -textInputRange.moveEnd("character", -len);
                    end += normalizedValue.slice(0, end).split("\n").length - 1;
                }
            }
        }
    }

    return {
        start: start,
        end: end
    };
}

/* SETS CARET POSITION */
function setCaretPosition(el, caretPos) {

    el.value = el.value;

    // ^ this is used to not only get "focus", but
    // to make sure we don't have it everything -selected-
    // (it causes an issue in chrome, and having it doesn't hurt any other browser)

    if (el !== null) {

        if (el.createTextRange) {
            var range = el.createTextRange();
            range.move('character', caretPos);
            range.select();
            return true;
        }

        else {
            // (el.selectionStart === 0 added for Firefox bug)
            if (el.selectionStart || el.selectionStart === 0) {
                el.focus();
                el.setSelectionRange(caretPos, caretPos);
                return true;
            }

            else  { // fail city, fortunately this never happens (as far as I've tested) :)
                el.focus();
                return false;
            }
        }
    }
}

Then on document ready I apply a keyup event listener to the fields I want to be checked, but I only listen for keys that can actually modify the content of the field (I skip "Shift" key for example...), and if user hits "Esc" I restore the original value of the field...

  $('.updatablefield', $('#myform')).keyup(function(e) {
    myfield=this.id;
    myfieldname=this.name;
    el = document.getElementById(myfield);
    // or the jquery way:
    // el = $(this)[0];
      if (e.keyCode == 27) {                                 // if esc character is pressed
        $('#'+myfield).val(original_field_values[myfield]); // I stored the original value of the fields in an array...
        // if you only need to do the initial letter uppercase, you can apply it here directly like this:
        initialCap(el);
      }                                                    // end if (e.keyCode == 27)
      // if any other character is pressed that will modify the field (letters, numbers, symbols, space, backspace, del...)
      else if (e.keyCode == 8||e.keycode == 32||e.keyCode > 45 && e.keyCode < 91||e.keyCode > 95 && e.keyCode < 112||e.keyCode > 185 && e.keyCode < 223||e.keyCode == 226) {
        // if you only need to do the initial letter uppercase, you can apply it here directly like this:
        initialCap(el);
      } // end else = if any other character is pressed                      //
  }); // end $(document).keyup(function(e)

You can see a working fiddle of this example here: http://jsfiddle.net/ZSDXA/

JohnRDOrazio
  • 1,358
  • 2
  • 15
  • 28
2

Simply put:

$this.val(val);

$(document).ready(function() {    
    $('input').on('keypress', function(event) {
        var $this = $(this),
            val = $this.val();

        val = val.toLowerCase().replace(/\b[a-z]/g, function(letter) {
            return letter.toUpperCase();
        }); 
        console.log(val);
        $this.val(val);
    });
});

As @roXon has shown though, this can be simplified:

$(document).ready(function() {
    //alert('ready');

    $('input').on('keypress', function(event) {
        var $this = $(this),
            val = $this.val();

        val = val.substr(0, 1).toUpperCase() + val.substr(1).toLowerCase();
        $this.val(val);
    });
});

An alternative, and better solution in my opinion, would be to only style the element as being capitalized, and then do your logic server side.

This removes the overhead of any javascript, and ensures the logic is handled server side (which it should be anyway!)

Community
  • 1
  • 1
Curtis
  • 101,612
  • 66
  • 270
  • 352
1

only use this This work for first name in capital char

style="text-transform:capitalize;

Like

<asp:TextBox ID="txtName" style="text-transform:capitalize;" runat="server" placeholder="Your Name" required=""></asp:TextBox>
S.I.
  • 3,250
  • 12
  • 48
  • 77
Raghuveer
  • 21
  • 1
0
$('input').on('keyup', function(event) {
    $(this).val(function(i, v){
        return v.replace(/[a-zA-Z]/, function(c){
           return c.toUpperCase();
        })
    })
});

http://jsfiddle.net/AbxVx/

Ram
  • 143,282
  • 16
  • 168
  • 197
0

This will do for every textfield call function on keyup

where id is id of your textfield and value is value you type in textfield

function capitalizeFirstLetter(value,id)
{

    if(value.length>0){

        var str= value.replace(value.substr(0,1),value.substr(0,1).toUpperCase());
        document.getElementById(id).value=str;

    }

}
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
0
   $('.form-capitalize').keyup(function(event) {
        var $this = $(this),
        val = $this.val(),
        regex = /\b[a-z]/g;
        val = val.toLowerCase().replace(regex, function(letter) {
            return letter.toUpperCase();
        });
        this.value = val;
        // I want this value to be in the input field.
      console.log(val);
    });
  • This answer doesn't provide what and why you have done it like this. Please provide more information, thanks in advance! – King Reload May 02 '17 at 08:15