HTML Yazı Alanına Sadece Büyük Harf Yazdırmak

HTML JavaScript JS TextBox Input Input Text Doğrulama Uppercase Vanilla JS

Bir html sayfasında yazı alanına yalnızca büyük harf ile giriş yaptırtmak için sadece JavaScript kodu ile harfler kontrol edilip büyük harfe çevrilebilir;

Kod

// HTML text field;
<input id="txtName" class="form-control uppercase-only" type="text" runat="server" />

Kod

// Vanilla JS Code;
<script type="text/javascript">
    
    var forceKeyPressUppercase = function(e) {
        var el = e.target;
        var charInput = e.keyCode;
        
        console.log("e.key", e.key);
        console.log("charInput", charInput);
        
        if (!e.ctrlKey && !e.metaKey && !e.altKey) { // no modifier key
            
            if (((charInput >= 97) && (charInput <= 122)) || (charInput == 305 || charInput == 287 || charInput == 252 || charInput == 351 || charInput == 231 || charInput == 246 || charInput == 105)) { // lowercase
            
                var newChar = charInput - 32;
                                
                switch(charInput)        // Turkish Chars;
                {
                    case 105:            // i
                    newChar = 304;        // İ
                    break;
                
                    case 305:            // ı
                    newChar = 73;        // I
                    break;
                    
                    case 287:            // ğ
                    newChar = 286;        // Ğ
                    break;
                    
                    case 252:            // ü
                    newChar = 220;        // Ü
                    break;
                    
                    case 351:            // ş
                    newChar = 350;        // Ş
                    break;
                    
                    case 231:            // ç
                    newChar = 199;        // Ç
                    break;
                    
                    case 246:            // ö
                    newChar = 214;        // Ö
                    break;
                    
                    default:
                    break;
                }
                
                var start = el.selectionStart;
                var end = el.selectionEnd;
                el.value = el.value.substring(0, start) + String.fromCharCode(newChar) + el.value.substring(end);
                el.setSelectionRange(start + 1, start + 1);
                e.preventDefault();
                
            }
        }
    };

    document.querySelectorAll(".uppercase-only").forEach(function (current) {
        current.addEventListener("keypress", forceKeyPressUppercase);
    });

</script>

Kaynaklar

  1. Forcing INPUT text to uppercase , the-art-of-web.com, 22.04.2024 tarihinde alındı.


Beğen