IT Forward
IT Forward

Reputation: 395

Making Caps to the first letter automatically

I want to make the first letter in a text box to be capital but i have no idea on how i can apply it. e.g sitholimela ----> Sitholimela

I want to apply this to a text box.

Thanks for your help.

Upvotes: 10

Views: 17332

Answers (4)

Naresh Kumar Nakka
Naresh Kumar Nakka

Reputation: 520

Please try this. It works.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title>Capitalizing first letter in a textbox</title>
  <script type="text/javascript">
  function capitalize(textboxid, str) {
      // string with alteast one character
      if (str && str.length >= 1)
      {       
          var firstChar = str.charAt(0);
          var remainingStr = str.slice(1);
          str = firstChar.toUpperCase() + remainingStr;
      }
      document.getElementById(textboxid).value = str;
  }
  </script>
 <body>
  <form name="myform" method="post">
      <input type="text" id="mytextbox" onkeyup="javascript:capitalize(this.id, this.value);">
  </form>
 </body>
</html>

Upvotes: 11

Billy Moon
Billy Moon

Reputation: 58551

Working demo...

http://jsfiddle.net/billymoon/mzXLc/1/

HTML

<input type="text" id="targetBox">

Javascript

var capitalize = function(e){
    // if the first letter is lowercase a-z
    // ** don't run the replace unless required, to permit selecting of text **
    if(this.value.match(/^[a-z]/)){
        // replace the first letter
        this.value = this.value.replace(/^./,function(letter){
            // with the uppercase version
            return letter.toUpperCase();
        });
    }
}

// listen to key up in case of typeing, or pasting via keyboard
// listen to mouseup in case of pasting via mouse
// prefer `up` events as the action is complete at that point
document.getElementById('targetBox').addEventListener('keyup', capitalize);
document.getElementById('targetBox').addEventListener('mouseup', capitalize);

Upvotes: 4

gvee
gvee

Reputation: 17161

CSS

input[type=text] {
    text-transform: capitalize;
}

This will make the text appear in this way.

DEMO: http://jsfiddle.net/gvee/csC8K/

Upvotes: 9

Paul S.
Paul S.

Reputation: 66344

To do this in JavaScript, get the node, and replace it's value with your transformation

var textbox = document.getElementById('myTextboxId');

textbox.value = textbox.value.charAt(0).toUpperCase() + textbox.value.slice(1);

MDN pages

Upvotes: 7

Related Questions