90

JS:

<script type="text/css">
$(function() {
    $('#upper').keyup(function() {
        this.value = this.value.toUpperCase();
    });
});
</script>

HTML

<div id="search">
        <input type="radio" name="table" class="table" value="professor" tabindex="1" /> Professor
        <input type="radio" name="table" class="table" value="department" tabindex="2" /> Department
        <input type="radio" name="table" id="upper" class="table" value="course" tabindex="3" /> Course
        <input type="text" name="search" class="keywords" value="Select an option..." onclick="this.value='';" onfocus="this.select()" onblur="this.value=!this.value?':this.value;" tabindex="4"  />
        <div id="content"> </div>
    </div>

Why is this still not working?? Just trying to call div ".keywords" from JS.

2
  • I wish I had time to put what I believe is the best answer here. It's to handle the keypress event and change the keycode to upper case if applicable, it's easier than it sounds to make cross browser compatible, but I think it's the best solution. Apr 22, 2011 at 16:17
  • Actually the solution I was thinking of only works for IE... e.which is readonly in FF and WebKit, but IE lets you change e.keyCode. Try this in IE jsfiddle.net/48fSq/1 Apr 22, 2011 at 21:57

15 Answers 15

276

I think the most elegant way is without any javascript but with css. You can use text-transform: uppercase (this is inline just for the idea):

<input id="yourid" style="text-transform: uppercase" type="text" />

Edit:

So, in your case, if you want keywords to be uppercase change: keywords: $(".keywords").val(), to $(".keywords").val().toUpperCase(),

13
  • 2
    @Tim - You're not allowed to have end tag's for INPUTs: w3.org/TR/html401/interact/forms.html#edef-INPUT Apr 22, 2011 at 15:47
  • 9
    will the user input really be uppercase or is it just for display here ?
    – BiAiB
    Apr 22, 2011 at 15:48
  • 45
    Need to keep in mind that retrieving the value using (just) JavaScript will return the original text; i.e. not uppercase. Example here
    – Shaz
    Apr 22, 2011 at 15:49
  • 24
    If you just want it to look upper-case, than this may be true. However, if you want the actual input.value to be upper case, you'll have to duplicate your efforts before submitting the form, or using input.value, which makes it not so elegant. Apr 22, 2011 at 16:08
  • 6
    This simple idea just saved me from the fiery depths of event interaction witch's brew hell. May the system fan wind be always at your back, May the heat sink shine warm upon your face. Apr 23, 2015 at 19:01
57

Javascript string objects have a toLocaleUpperCase() function that makes the conversion itself easy.

Here's an example of live capitalisation:

$(function() {
    $('input').keyup(function() {
        this.value = this.value.toLocaleUpperCase();
    });
});

Unfortunately, this resets the textbox contents completely, so the user's caret position (if not "the end of the textbox") is lost.

You can hack this back in, though, with some browser-switching magic:

// Thanks http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/
function getCaretPosition(ctrl) {
    var CaretPos = 0;    // IE Support
    if (document.selection) {
        ctrl.focus();
        var Sel = document.selection.createRange();
        Sel.moveStart('character', -ctrl.value.length);
        CaretPos = Sel.text.length;
    }
    // Firefox support
    else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
        CaretPos = ctrl.selectionStart;
    }

    return CaretPos;
}

function setCaretPosition(ctrl, pos) {
    if (ctrl.setSelectionRange) {
        ctrl.focus();
        ctrl.setSelectionRange(pos,pos);
    }
    else if (ctrl.createTextRange) {
        var range = ctrl.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
}


// The real work

$(function() {
    $('input').keyup(function() {
        // Remember original caret position
        var caretPosition = getCaretPosition(this);

        // Uppercase-ize contents
        this.value = this.value.toLocaleUpperCase();

        // Reset caret position
        // (we ignore selection length, as typing deselects anyway)
        setCaretPosition(this, caretPosition);
    });
});

Ultimately, it might be easiest to fake it. Set the style text-transform: uppercase on the textbox so that it appears uppercase to the user, then in your Javascript apply the text transformation once whenever the user's caret focus leaves the textbox entirely:

HTML:

<input type="text" name="keywords" class="uppercase" />

CSS:

input.uppercase { text-transform: uppercase; }

Javascript:

$(function() {
    $('input').focusout(function() {
        // Uppercase-ize contents
        this.value = this.value.toLocaleUpperCase();
    });
});

Hope this helps.

13
  • 1
    +1 didn't thought of the loss of selection problem (and loss of cursor too). And it's so annoying when it happens. this is the best answer to me
    – BiAiB
    Apr 22, 2011 at 16:00
  • @Tomalak - In the first example, why not use focusout? Apr 22, 2011 at 16:00
  • 1
    @Jared: I have made the assumption that the OP wants the textbox contents to automatically be uppercased as the user types. I certainly would. Apr 22, 2011 at 16:02
  • @Tomalak - Yeesh. So much simpler to modify on focusout... But that is the first sentence. I'd at least make the argument, but this isn't my answer, so it's just a comment. :) Apr 22, 2011 at 16:03
  • 1
    @SJnawali The problem is that you didn't read the whole answer. text-transform: uppercase is for during typing; the value is then overwritten with its uppercase equivalent when focus leaves the control. Mar 13, 2013 at 11:45
13

If you purpose it to a html input, you can easily do this without the use of JavaScript! or any other JS libraries. It would be standard and very easy to use a CSS tag text-transform:

<input type="text" style="text-transform: uppercase" >

or you can use a bootstrap class named as "text-uppercase"

<input type="text" class="text-uppercase" >

In this manner, your code is much simpler!

11

Solutions using value.toUpperCase seem to have the problem that typing text into the field resets the cursor position to the end of the text. Solutions using text-transform seem to have the problem that the text submitted to the server is still potentially lowercase. This solution avoids those problems:

function handleInput(e) {
   var ss = e.target.selectionStart;
   var se = e.target.selectionEnd;
   e.target.value = e.target.value.toUpperCase();
   e.target.selectionStart = ss;
   e.target.selectionEnd = se;
}
<input type="text" id="txtTest" oninput="handleInput(event)" />

8

Can also do it this way but other ways seem better, this comes in handy if you only need it the once.

onkeyup="this.value = this.value.toUpperCase();"
5

try:

$('#search input.keywords').bind('change', function(){
    //this.value.toUpperCase();
    //EDIT: As  Mike Samuel suggested, this will be more appropriate for the job
    this.value = this.value.toLocaleUpperCase();
} );
8
  • You need to assign the result somewhere, and this won't work as the user types as change only fires when the control loses focus. Apr 22, 2011 at 15:47
  • For user input, .toLocaleUpperCase is probably more appropriate. developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… Apr 22, 2011 at 15:47
  • @Mike Samuel You're true, I didnt know that method. Hope it is cross browers, since I saw it on Msdn, i'll update my answer
    – BiAiB
    Apr 22, 2011 at 15:50
  • @BiAiB: This is broken; you are not assigning the uppercase version of the text to anything. Apr 22, 2011 at 15:59
  • 1
    @BiAiB, toLocaleUpperCase is available cross-browser but it's behavior is not necessarily identical across different browser in the same locale as it obviously depends on the version of the character mappings present on the local machine. It's specified in section 15.5.4.17 of the EcmaScript language standard. cheers, mike Apr 23, 2011 at 1:25
4

I think the most easiest way to do is by using Bootstrap's class ".text-uppercase"

<input type="text" class="text-uppercase" />
1
  • How is this different from other answers?
    – Kurohige
    Apr 25, 2020 at 16:25
3

I couldn't find the text-uppercase in Bootstrap referred to in one of the answers. No matter, I created it;

.text-uppercase {
  text-transform: uppercase;
}

This displays text in uppercase, but the underlying data is not transformed in this way. So in jquery I have;

$(".text-uppercase").keyup(function () {
    this.value = this.value.toLocaleUpperCase();
});

This will change the underlying data wherever you use the text-uppercase class.

2
onBlur="javascript:{this.value = this.value.toUpperCase(); }

will change uppercase easily.

Demo Here

0

This answer has a problem:

style="text-transform: uppercase"

it also converts the place holder word to upper case which is inconvenient

placeholder="first name"

when rendering the input, it writes "first name" placeholder as uppercase

FIRST NAME

so i wrote something better:

onkeypress="this.value = this.value + event.key.toUpperCase(); return false;"

it works good!, but it has some side effects if your javascript code is complex,

hope it helps somebody to give him/her an idea to develop a better solution.

0

Here we use onkeyup event in input field which triggered when the user releases a Key. And here we change our value to uppercase by toUpperCase() function.

Note that, text-transform="Uppercase" will only change the text in style. but not it's value. So,In order to change value, Use this inline code that will show as well as change the value

<input id="test-input" type="" name="" onkeyup="this.value = this.value.toUpperCase();">

Here is the code snippet that proved the value is change

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
	<form method="get" action="">
		<input id="test-input" type="" name="" onkeyup="this.value = this.value.toUpperCase();">
		<input type="button" name="" value="Submit" onclick="checking()">
	</form>
	<script type="text/javascript">
		function checking(argument) {
			// body...
			var x = document.getElementById("test-input").value
			alert(x);
		}
		
		
	</script>
</body>
</html>

0
0
<input id="name" data-upper type="text"/>
<input id="middle" data-upper type="text"/>
<input id="sur" data-upper type="text"/>

Upper the text on dynamically created element which has attribute upper and when keyup action happens

$(document.body).on('keyup', '[data-upper]', function toUpper() {
  this.value = this.value.toUpperCase();
});
1
  • upper is not a valid attribute, instead you should use data-upper instead. The main reason behind using text-transform in CSS alongside something like this is so that the user doesn't see it get converted from lower to uppercase. Your function is also anonymous, there's no point in giving it a name :)
    – zanderwar
    May 3, 2019 at 2:10
-1
**JAVA SCRIPT**
<html>
<body>
<script>
function @ToCaps(obj)
{
obj.value=obj.value.toUpperCase();
}
</script>
<input type="text" onkeyup=@ToCaps(this)"/>
</body>
</html>

**ASP.NET**
Use a css style on the text box, write css like this:

.ToCaps { text-transform: uppercase; }

<asp:TextBox ID="TextBox1" runat="server" CssClass="ToCaps"></asp:Te writxtBox>

**OR**
simply write this code in textbox
<asp:TextBox ID="TextBox1" runat="server" style="text-transform:uppercase"></asp:TextBox>


 **1.Note you don't get intelligence until you type up to style="**  
1
  • 1
    It is never ever going to work this way with <script type="text/css">
    – swapnesh
    Jul 9, 2013 at 5:17
-1

Javascript has a toUpperCase() method. http://www.w3schools.com/jsref/jsref_toUpperCase.asp

So wherever you think best to put it in your code, you would have to do something like

$(".keywords").val().toUpperCase()
4
  • How would I do this for the Course call only??
    – Jshee
    Apr 22, 2011 at 15:51
  • There are a bunch of ways to do it. Quickest and easiest is just put it inside of case for "course".
    – user715714
    Apr 22, 2011 at 16:14
  • How do I do this for: case 'course': phppage = 'course'; ext = '.php?cID='; break;
    – Jshee
    Apr 22, 2011 at 16:26
  • Sorry Im a bit confused how to implement it (as basic as it is)
    – Jshee
    Apr 22, 2011 at 16:26
-1

you can try this HTML

<input id="pan" onkeyup="inUpper()" />

javaScript

function _( x ) {
  return document.getElementById( x );
}
  // convert text in upper case
  function inUpper() {
    _('pan').value = _('pan').value.toUpperCase();
  }

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.