0

I would like to know if there is better way to this exercice. Here it is : Create a form that contain a textbox ;after the user enter the text ,all the letters will be converted to lowercase as soon as he or she clicks elsewhere in the form( hint: use change onChange event handler).

I have written this code :

 <!DOCTYPE html>
 <html lang="en">
 <head>
 <meta charset="UTF-8">
 <title>Event</title>
 </head>
 <body>
 <form>
     Username : <input type="text" id="username"><br>

 <input type="submit" value="button">

 </form>
 <script type="text/javascript">

 var  username = document.getElementById("username");

 username.onchange = function(){
 username.value = username.value.toLowerCase();
 };


 </script>
 </body>
 </html>

Basically i'm replacing the content of the textbox by the formatted

2 Answers 2

1

Might be too easy, but setting the text over a style to lowercase transform doesn't allow uppercase :)

function toLower(element) {
   if (element && element.value) {
     element.value = element.value.toLowerCase();
     var target = document.getElementById('realvalue');
     target.innerHTML = element.value;
   }
}
<input type="text"  onblur="toLower(this)" />

<div id="realvalue"></div>

Sign up to request clarification or add additional context in comments.

5 Comments

Unfortunately, whatever is in the input box is still submitted in the same case the user originally typed it when you're only using text-transform. You'll have to use strtolower() (if you're using PHP) on the receiving end to keep the lower case.
@ScottKaye You are right, i added an onblur to do it (and added a display function to show it for sure :D)
Nice! Of course, if we're being super picky, that only works if the user has Javascript enabled ;)
indeed, but it's a javascript solution that was asked for :D
your code doesn't allow typing uppercase letter while in the box, anyway ,it's a good example of code re-use ,clever and that's cool
1

But, if all the letters will be converted to lowercase as soon as he or she clicks elsewhere in the form, your code work correctly... http://jsfiddle.net/b6xwde62/

 <form>
     Username : <input type="text" id="username"><br>

 <input type="submit" value="button">

 </form>
 <script type="text/javascript">
 var  username = document.getElementById("username");

 username.onchange = function(){
 username.value = username.value.toLowerCase();
 };
 </script>

1 Comment

I know that it works ,i wanted a more clever(or efficient) way to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.