开发者

How can I capitalize the first letter of an input?

I'm currently trying to capitalize the very first letter from an input开发者_如何学Python.

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


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


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


$('#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.


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


You must use

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

without <input />

then in CSS:

fieldset input {
    text-transform: capitalize;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜