Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Css trying to make first character in input field uppercase

Tags:

html

css

input

I am trying to make the first character in a input field uppercase.

So far I have tried:

input:first-letter {text-transform:capitalize !important}
input:first-letter {text-transform:uppercase !important}

I have also tried to make the input field styled display:block; and display:inline-block; but with no luck.

I am using the latest version of chrome. If I look in the inspector the

input:first-letter {text-transform:capitalize !important} is flagged to be active but it does not work.

I am open to any Jquery solutions as well

Thanks,

like image 283
user2722667 Avatar asked Dec 02 '16 20:12

user2722667


1 Answers

:first-letter wont work on input field. but it works without that.

So change it as input {text-transform:capitalize;} it works fine. see demo

it works fine without !important

input {text-transform:capitalize;}
<input/>

As you have mentioned in pure css way i have added the above method

Limitation: It will capitalize all words in the input box. In pure CSS it is not possible to capitalize only the first word as of now. you have to try the jquery way to do this as given below

Using jquery:-

using keyup event

$('input').keyup(function(){
    if($(this).val().length>0){
      var character = $(this).val().charAt(0);
      if(character!=character.toUpperCase()){
          $(this).val($(this).val().charAt(0).toUpperCase()+$(this).val().substr(1));
       }
     }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input/>

To work even on mouse events:- (like cut paste in mouse)

Using propertychange event by $('input').bind('input propertychange', function() {

$('input').bind('input propertychange', function() {
    if($(this).val().length>0){
      var character = $(this).val().charAt(0);
      if(character!=character.toUpperCase()){
          $(this).val($(this).val().charAt(0).toUpperCase()+$(this).val().substr(1));
       }
     }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input/>
like image 111
jafarbtech Avatar answered Oct 04 '22 05:10

jafarbtech