38

I want to convert lowercase chars to uppercase as the user types using javascript. Any suggestions are welcome.

I have tried the following:

$("#textbox").live('keypress', function (e) {
    if (e.which >= 97 && e.which <= 122) {
        var newKey = e.which - 32;
        // I have tried setting those
        e.keyCode = newKey;
        e.charCode = newKey;
    }
});
Butcher
  • 395
  • 1
  • 3
  • 4

13 Answers13

58
css

#textbox{text-transform:uppercase}
kennebec
  • 102,654
  • 32
  • 106
  • 127
  • 1
    .. but then you can catch the "onchange" event and update the value to actual uppercase characters (if you access the value of the input box, it is still lowercase letters) – naivists Apr 06 '11 at 19:06
  • 3
    It works now - the first version had `upper-case` instead of `uppercase`. :) +1 from me as this is a clever answer but doesn't actually change the value of the textbox. – Andrew Hare Apr 06 '11 at 19:07
  • This is an elegant solution. Server-side usually needs to handle normalizing the input anyway. I did not know CSS could do this. – Pete May 02 '12 at 14:16
  • 1
    I know the OP has asked how to do it with _JavaScript_, however I would argue this is a more elegant and efficient way to do it. Also it has to be considered much more maintainable than this sort of thing: `if (e.which >= 97 && e.which <= 122) {`. – crmpicco Aug 28 '13 at 16:00
  • 4
    `text-transform:uppercase` also makes HTML 5 `placeholder` text uppercase on your input box (I only tested in Chrome 41). didn't like that, so I went with JavaScript solution instead. – Phil M Apr 09 '15 at 11:28
  • only problem is that it uc's the placeholder as well :( – dlchambers Sep 25 '15 at 19:45
  • This is a tidy solution. But on the other hand if you have validation on the input that requires upper case, ie - British postal code etc, it wont actually be upper case, just the style – Johnn5er Jan 27 '17 at 12:09
26
$("#textbox").bind('keyup', function (e) {
    if (e.which >= 97 && e.which <= 122) {
        var newKey = e.which - 32;
        // I have tried setting those
        e.keyCode = newKey;
        e.charCode = newKey;
    }

    $("#textbox").val(($("#textbox").val()).toUpperCase());
});
Shaz
  • 15,637
  • 3
  • 41
  • 59
  • Using `Event.charCode` will trigger a warning in JS consoles. That warning being: `The 'charCode' property of a keyupevent should not be used. The value is meaningless.` I'm not sure why you're using it when you're already using `Event.which` and `Event.keyCode`. –  Apr 06 '11 at 19:07
  • @MattMcDonald: I just took the code from the example and hoped to answer what the OP wanted. ;) – Shaz Apr 06 '11 at 19:09
  • This works. It just looks ungly because you can see the text getting changed. I think this together with the CSS text transform is the best solution. Thank you – Butcher Apr 07 '11 at 00:32
  • You can't see the text being changed if you use keydown instead of keyup. – BobRodes Sep 14 '12 at 19:27
  • 3
    Cursor position is lost. The block in if does nothing. – Danubian Sailor Aug 27 '13 at 14:59
  • e.currentTarget.value = e.currentTarget.value.toUpperCase(); inside the function, looks nicer that all of those jQuery calls. Looks more simple, and works better when you need to bind several fields. Another issue is that keydown event doesn't works as well as keyup does, because the value always miss the last typed digit. I think the Butcher solution is the best for this case. – jairhumberto Oct 08 '14 at 14:30
  • but if you press the back (arrow) key, this function sent you to the finish of the value =( – Marcelo Lujan Aug 18 '16 at 20:59
9

This might be a nice workaround. Just set this in your CSS:

input#textbox {
    text-transform: uppercase;
}

If you post the data to a server side script (lets say php) you can always do something like this:

$upper_data = strtoupper($_POST['textbox']);
Andres SK
  • 10,779
  • 25
  • 90
  • 152
5

Hi this code works fine on input and textarea without delay or capitalization change

$("#input").on('input', function(evt) {
              var input = $(this);
              var start = input[0].selectionStart;
              $(this).val(function (_, val) {
                return val.toUpperCase();
              });
              input[0].selectionStart = input[0].selectionEnd = start;
            });

mix from https://stackoverflow.com/a/7944108/1272540 and https://stackoverflow.com/a/13155583/1272540

jsFiddle

Community
  • 1
  • 1
Yann86
  • 1,018
  • 10
  • 16
3

try this css script it's work for me.

<style>    
input{text-transform:uppercase};
</style>    

for information, what you see maybe upper case but it's actually still what you type like if you type "Test" it shown as "TEST" but when your get by val() it shown as "Test".

if you want to make it be upper case for real then add some script below on event like blur from the object or elenent as you need.

$(this).val($(this).val().toUpperCase());

And if you want to use for specific object add some extra script like what i used by now

input[attr]{
text-transform:uppercase;
}

input[attr='value']{
text-transform:uppercase;
}
  • i have use it on chrome and mozilla. it work fine for me. may be you could help with another browser, and share it with the others. thanks – percayahati Apr 15 '14 at 07:08
  • 2
    The problem with this solution is that it will only show as uppercase on screen, but if you need text as uppercase in database, this solution will not work as expected. – jairhumberto Oct 08 '14 at 14:09
2
function changeToUpperCase(event,obj) {
    charValue = (document.all) ? event.keyCode : event.which;
    if (charValue!="8" && charValue!="0" && charValue != "27"){
        obj.value += String.fromCharCode(charValue).toUpperCase();
        return false;
    }else{
        return true;
    }
}

<input id="txtId" type="text" onkeypress="return changeToUpperCase(event,this)" />

Edit:

The most simplest way is by using css:

#txtId {text-transform:uppercase}
Vishrant
  • 15,456
  • 11
  • 71
  • 120
1

Since you tagged this as a jQuery question as well, here's a simple (well, fairly simple) jQuery solution:

$('#text_statute_section').on('keypress', function(event) {
    if(null !== String.fromCharCode(event.which).match(/[a-z]/g)) {
        event.preventDefault();
        $(this).val($(this).val() + String.fromCharCode(event.which).toUpperCase());
    }
});

Using keypress prevents the "bounce" effect that keyup has (keydown also does, but event.which doesn't distinguish directly between upper and lower case here--shift key check is messy owing to caps lock). Also, this operates on the input character, converts it to uppercase, and then appends it to the existing value, rather than first appending and then converting the whole thing to uppercase as most of the other solutions I've seen do. Finally, it actually converts the character rather than applying a formatting style to it as CSS does. All this gives better control, especially in situations where some characters need to be forced to uppercase and some not, such as in serial numbers or the like.

EDIT: (four years later)!

I've never been happy with how jQuery/javascript handles changing keys to uppercase as they are typed in. I've been over all the suggestions in this post, and none of them (least of all mine) quite work flawlessly. This is irritating to me, as it was a simple matter in the old VB6 days to change the KeyAscii character that was passed to the KeyPress event. Anyway, quite by accident, I have found a sort of "black art" solution that does work flawlessly as far as I have tested it. Meaning it works in Chrome, it correctly handles any cursor position on the text, it (with some work) doesn't change the browser's focus behavior, and it reliably changes to uppercase without any sort of jittery showing of lowercase first. While the CSS solution also does all of this, as others have observed it has the drawback of having to programmatically force the underlying characters to uppercase when you need the actual string to work with, which can be a hassle to keep track of and therefore doesn't scale well. So, I thought I might write this up, in case someone finds it useful.

This solution does depend on Josh Bush's little (180 lines of code, for those worried about dependency bloat) Masked Input Plugin from digitalbush, which is rock solid and does what it does very well. If you change event.which to another value, and call the mask() method afterwards (specify the keypress handler first and the mask second in your code) the change will persist.

Here's a bit of code:

$.mask.definitions['b'] = '[A-Z, ]';

$('#txtMyInput').on('keypress', function(e) {
    e.which =     String.fromCharCode(e.which).toUpperCase().charCodeAt(0);
})
.mask('b?bbbbbbbbbbbbbbbbbbb', { placeholder: '' })

Mask doesn't support very many mask types natively: literals, alpha, numeric and alphanumeric are it. If you want punctuation or whatever you have to roll your own using regex. (If you do this, you'll need to keep in mind that the same regex match is applied to each character one at a time, without consideration of the other characters, so you can't do anything fancy). In my particular case, I needed all caps, plus spaces and commas. The ? in the mask string means the following characters are optional, so this one gives me up to 20 characters. Since I didn't need any mask to show, I used an empty string for a placeholder.

That all works perfectly, except for the one small problem: if you want to keep the way the browser selects the text when tabbing into the field, you have to do extra work. I wound up having to hack the mask code to get what I wanted.

I first tried simply selecting the text in a focus event handler, which normally works when I call focus() from a keydown handler. It didn't work here; the cursor just got set to the end of the text as it would on a mouse click there. I tried changing the placeholder to a space. This resulted in padding the text with enough spaces to fill up the limit specified, and selecting the whole thing.

I tried some of the techniques here, but the best of them (i.e. the one that actually worked in this case) still doesn't apply the highlight until key up, which means there's a lag in when it happens, and it doesn't happen at all if you hold the key down till it repeats and happen to let go when the focus is in the box.

So I dug into the mask code. As it turns out, the plugin also has a focus event handler that it uses to set up the mask indicator (say, (___) ___-___-____ for a phone) in the box when you focus on it. This is the behavior you want most of the time, but not here, because it replaces the selected text with the selected text concatenated to the part of the mask indicator that hasn't been filled yet. When you don't have a mask indicator, this has the effect of deselecting the text in the box just as would happen if you programmatically assigned the text value of the box.

I decided to hack the mask code a bit. I first tried commenting out the entire focus event handler, which had the effect of not showing the input mask on other fields where I wanted it. So, I found a less invasive alternative. I changed this (currently jquery.maskedinput.js, line 164):

}).on("focus.mask", function() {
    if (!input.prop("readonly") { 
        // etc.

to this:

}).on("focus.mask", function() {
    if (!input.prop("readonly") && settings.placeholder.length > 0) {

This bypasses setting up the mask indicator if you have set your placeholder to a blank string, which allows the browser's native focus behavior to take place.

One more thing: if you are using the focus() method to focus on the text box (for example, to rescue the data entry user from the browser's tendency to wander to parts unknown upon use of the tab key), you'll have to call the select() method in the focus event handler to properly highlight the text (keybdFocus is a flag I set when I call the focus() event from a keydown handler, so as to distinguish from a mouse-generated focus):

$('#txtMyInput').on('keypress', function(e) {
    e.which = String.fromCharCode(e.which).toUpperCase().charCodeAt(0);
})
.mask('b?bbbbbbbbbbbbbbbbbbb', { placeholder: '' })
.focus(function() {
    if (kybdFocus) {
        kybdFocus = false;
        $(this).select();
    }
});

Summarizing the steps:

  1. Download Josh Bush's Masked Edit Plugin.
  2. Change the line of code in the plugin's focus handler.
  3. Set up a mask definition (if needed) to handle the characters you want.
  4. In your keypress event handler, use your favorite technique to change e.which to its uppercase equivalent. (Important: the call to the handler must precede the call to the mask() method in your code. The mask evaluates e.which to determine whether the candidate character fits the mask, and apparently the handler and the mask code are fired in the order in which they are specified.)
  5. Set the placeholder value to '' when you call the mask() method.
  6. If you hit the input box with a focus, call the select() method in your focus event handler.

Of course, if you just want to force characters to uppercase in the context of a typical masked edit box, you can omit steps 2 and 4. That's how I fell into this in the first place.

Community
  • 1
  • 1
BobRodes
  • 5,990
  • 2
  • 24
  • 26
  • 1
    It is not always correct to append the typed character to the current value. This makes it impossible to edit text elsewhere within the string (e.g., type "WORLD", then click to put the cursor at the beginning and try to make the value say "HELLO WORLD"... you'll get "WORLDHELLO "). – quietmint Jan 22 '13 at 19:10
  • Good point, user. I was borrowing from something I wrote where that wasn't an issue (I think), but it certainly could be. I'll run back and double check my code. Thanks! – BobRodes Feb 04 '13 at 21:49
1
$(document).ready(function () {
  $("#textbox").keyup(function (e) {
    var str = $(this).val();
    $("#textbox").val(str.toUpperCase());
  });
});
Christos Lytras
  • 36,310
  • 4
  • 80
  • 113
T rakesh
  • 11
  • 1
1

I know I'm quite late to the party, but I'd like to offer this:

(function ( $ ) {

  var displayUppercase = function ($element) {
    if ($element.val()) {
      $element.css('text-transform', 'uppercase');
    } else {
      $element.css('text-transform', 'none');
    }
  };

  $.fn.displayAsUppercase = function() {
    $(this).each(function() {
        var $element = $(this);
      displayUppercase($element);
      $element.on('input', function(){displayUppercase($element)});
    });
    return this;
    };

}( jQuery ));

It has these advantages:

  • Keeps the placeholder capitalization intact
  • Capitalizes the input immediately (on keydown)
  • Doesn't move the cursor
  • Capitalizes the value of the input if it's prepopulated

JS Fiddle here

Chris HG
  • 1,412
  • 16
  • 20
0

This is a solution I came up with, which also avoids the issues with placeholders changing to upper case, and does not mess around with the cursor position.

Caution: does not change the "value" of the field, only the display. For that see here: Updating an input's value without losing cursor position

$(function() {
    $("[data-uppercase='1']").on('keypress', function (e) {
        var $this = $(this);
        var placeholder = $this.attr('placeholder');
        if(placeholder && placeholder.length > 0) {
            this["_placeholder"] = placeholder;
            $this.attr('placeholder', '');
        }
        $this.css('text-transform', 'uppercase');
    }).on('keyup blur', function () {
        var $this = $(this);
        if ($this.val().length < 1) {
            $this.css("text-transform", "");
            $this.attr("placeholder", this["_placeholder"]);
            this["_placeholder"] = undefined;
        }
    });
});

Then add a data-uppercase attribute to the HTML element:

<input type="text" data-uppercase="1" />

Worked in Chrome, Firefox and IE9+.

Fiddle: https://jsfiddle.net/GarryPas/ptez7q0q/3/

Community
  • 1
  • 1
garryp
  • 5,508
  • 1
  • 29
  • 41
0
$(document).on('keypress', '.to-tr-upper-case', function (e) {
    var object=this;
    setTimeout(function () {
        var start=object.selectionStart;
        var end=object.selectionEnd;
        $(object).val($(object).val().toLocaleUpperCase('tr-TR'));
        object.selectionStart=start;
        object.selectionEnd=end;
    },100);
});
cArf
  • 81
  • 1
  • 5
-1

While the CSS + Server Side UCase approach is probably "best", here is a Client Side jQuery solution I use when the need arises:

$("#id").keyup(function() {
    $(this).val($(this).val().replace(/([a-z])/,function(s){return s.toUpperCase()}));
});

She's not pretty, but she'll get the job done!

Campbeln
  • 2,880
  • 3
  • 33
  • 33
  • No... it just Ups the case on keyup. are you seeing an issue in a specific browser @esp? – Campbeln Feb 14 '13 at 07:09
  • Had this thing in safari when changing the form field resulted in moving the cursor to the end of the field, as it is above it won't let you move cursor with arrows inside the field. Probably if you filter carefully on which keys not to touch the field it can work. But it's strange I can't find the way just to replace the character as it's typed, before it is inserted. Didn't look very hard though ;) – esp Feb 14 '13 at 11:29
  • Not pretty as you say, but certainly a lot simpler than the pretty solution I just posted. – BobRodes Jul 01 '16 at 20:06
-1
$("#id").keyup(function() {
    $(this).val($(this).val().replace(/([a-z])/,function(){
        return $("#id").toUpperCase();
    }));
});

small correction in the above script this will work perfectly now.

Tisho
  • 8,320
  • 6
  • 44
  • 52