Safirio
Safirio

Reputation: 125

How can I capitalize the first letter of an input?

I'm currently trying to capitalize the very first letter from an input.

Here's what I tryed :

fieldset input
{
    text-transform:capitalize;
}

But it doesn't work the way I want, as every word is capitalized.

I also tryed this :

fieldset input:first-letter
{
  text-transform:uppercase;
}

But it seems <input /> doesn't work at all with first-letter...

Anyway, do you have any idea of how to achieve this without javascript (or as little as possible) ?

Upvotes: 10

Views: 11962

Answers (5)

TommyZG
TommyZG

Reputation: 560

Inputs can't have first letter capitalized only with CSS, not even :first-letter pseudoselector. We have to use Javascript.

We will use class name capitalized on every input for which we want to have the first letter capitalized.

HTML:

<input type="text" class="capitalized" />

The idea is to listen for change on input (focusout), take the value, capitalize first letter, join it with the rest of the value and set it as new value. You can use keyup, but that becomes overkill after the first keyup - nothing will change there.

JS (jQuery flavor):

$('.capitalized').on('change', function () {
    let entered = $(this).val();
    let firstLetter = entered.charAt(0).toUpperCase();
    let rest = entered.substring(1);
    $(this).val(firstLetter + rest);
});

Upvotes: 0

men0
men0

Reputation: 1

You must use

<fieldset>
            <legend>DATA...</legend>
            <input type="text" class="inputName" placeholder="Введите имя">

without <input />

then in CSS:

fieldset input {
    text-transform: capitalize;
}

Upvotes: -1

Himanshu Saini
Himanshu Saini

Reputation: 812

$('#INPUT_ID').keyup(function(){
    if($(this).val().length>0 && $(this).val().length<5){
        $(this).val($(this).val().charAt(0).toUpperCase()+$(this).val().substr(1));
     }
});

Can't use length==1, as it doesn't work if user types fast.

Upvotes: 1

Sjoerd
Sjoerd

Reputation: 75689

Impossible. It is possible with Javascript, or by putting only the first word within a span.

Upvotes: 3

Babiker
Babiker

Reputation: 18818

JS: str.charAt(0).toUpperCase();

Upvotes: 7

Related Questions