10

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) ?

2
  • Interestingly, your :first-letter CSS does work for a textarea. Neat.
    – Joshua
    Commented Aug 11, 2014 at 12:26
  • Never force a capital letter in the names of people. Many have names like "Hans von Axelkrok" or "" Greta af Klint "
    – Tony von
    Commented Nov 16, 2021 at 15:07

5 Answers 5

7

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

1
  • Thanks, I'll try this with a jQuery selector, then.
    – Safirio
    Commented Jun 15, 2010 at 15:04
3

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

1
  • 4
    You can't have span elements in an input text field. Commented Jun 15, 2010 at 14:50
1
$('#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.

0

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);
});
-1

You must use

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

without <input />

then in CSS:

fieldset input {
    text-transform: capitalize;
}

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