Sai Krishna
Sai Krishna

Reputation: 59

Reverse case (Lowercase/Uppercase) of an input value character by character

By using one input text box and the input type allows only alphabets.The value entered is 'a' and it should be display outside the textbox as 'A'?

If we enter the alphabet small 'a' on input text then it will wanted to display capital 'A' on the outside of the box... The following is my html code:

<!DOCTYPE html>
   <html>
      <head>
         <!--<script type="text/javascript" href="check.js"></script>-->
      </head>
        <body>
          <input type="text">
             <script>
                function myFunction()
                {
                    var A = document.getElementById('input').value; 
                    console.log('alphabet'.toUpperCase());
                }
             </script>
       </body>
    </html>

Upvotes: 2

Views: 6661

Answers (3)

S Gabale
S Gabale

Reputation: 11

function reverseCase(str) {
    let newstr = str.split('');
    let newarr = [];
    //return newstr;
    for(i=0; i<newstr.length; i++) {
        if(newstr[i] == newstr[i].toLowerCase()){
            newarr.push(newstr[i].toUpperCase());
        }else 
        if(newstr[i] == newstr[i].toUpperCase()){
            newarr.push(newstr[i].toLowerCase());
        }
    } return newarr.join('');
}
console.log(reverseCase("Happy Birthday"))

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386816

You may use an event for immediatly update the result, while writing.

document.getElementById('input').addEventListener('keyup', function () {
    var input = document.getElementById('input').value;
    if (!input.match(/^[a-z]*$/i)) {
        document.getElementById('output').innerHTML = 'Wrong input';
        return;
    }
    document.getElementById('output').innerHTML = input.split('').map(function (a) {
        return a.match(/[a-z]/)  ? a.toUpperCase() : a.toLowerCase();
    }).join('');
});
<input type="text" id="input">
<div id="output"></div>

Upvotes: 1

cнŝdk
cнŝdk

Reputation: 32165

To show the input value with case reversed you should:

  1. Call your function in the onkeyup event of your input to update the preview immediately with the inputted string.

  2. And loop through your string and for each character test if it's in uppercase reverse it to lowercase or make it uppercase if it's lowercase.

Here's a Snippet DEMO:

function myFunction() {
  var A = document.getElementById('input').value;
  var output = '';
  for (var i = 0, len = A.length; i < len; i++) {
    var character = A[i];
    if (character == character.toLowerCase()) {
      // The character is lowercase
      output = output + character.toUpperCase();
    } else {
      // The character is uppercase
      output = output + character.toLowerCase();
    }
  }
  document.getElementById("preview").innerText = output;
}
<input id="input" type="text" pattern="[A-Za-z]" onkeyup="myFunction()" /><span id="preview"></span>

Upvotes: 2

Related Questions