Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Caps to the first letter automatically

Tags:

javascript

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.

like image 650
IT Forward Avatar asked Aug 20 '13 12:08

IT Forward


2 Answers

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);
like image 57
Billy Moon Avatar answered Sep 26 '22 09:09

Billy Moon


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>
like image 45
Naresh Kumar Nakka Avatar answered Sep 24 '22 09:09

Naresh Kumar Nakka