user198989
user198989

Reputation: 4663

Convert letter to lowercase letter automatically on keypress?

I want to convert letters automatically on keypress, tried this

$(document).on('keypress', function(e) {
  $("#nick").val().toLowerCase();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id=nick value="">

But when I write Uppercase letters, it doesnt convert to lowercase. Where I did mistake ?

Upvotes: 2

Views: 3512

Answers (3)

VIJAY P
VIJAY P

Reputation: 1433

you can also use below approach.

$(document).on('keyup','#nick',function(e){
    $(this).val(e.currentTarget.value.toLowerCase());
})

$(document).on('keyup','#nick',function(e){
    $(this).val(e.currentTarget.value.toLowerCase());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="nick" value="">

Upvotes: 0

Amin Jafari
Amin Jafari

Reputation: 7207

you gotta use the converted text somewhere, right? :)

$(document).on('keypress', function(e) {
    $("#nick").val($("#nick").val().toLowerCase());
});

UPDATE

if you use keyup it'll work as desired: DEMO

$(document).on('keyup', function(e) {
    $("#nick").val($("#nick").val().toLowerCase());
});

Upvotes: 1

Josh Crozier
Josh Crozier

Reputation: 241188

You aren't modifying the existing value. You need to re-assign the lowercase value:

$(document).on('keypress', function(e) {
  var value = $("#nick").val().toLowerCase();

  $("#nick").val(value);
});

Since the keypress event won't change the last character, I would suggest listening to the input event instead. The keyup event would work as well.

Example Here

$(document).on('input', function (e) {
  e.target.value = e.target.value.toLowerCase();
});

Without jQuery:

Example Here

document.addEventListener('input', function (e) {
  e.target.value = e.target.value.toLowerCase();
});

Upvotes: 4

Related Questions