Search code examples
javascriptextractonkeyup

Auto add first Char in Textfield based on Entered Value


I am attempting to add a textfield called Initials and based on what user enters in say fName textfield onkeyup auto complete initials textfield using first character only.

Here's my pathetic attempt, need help

<!DOCTYPE html>
<html>
<body>

<p>&nbsp;</p>
<p>Enter your name: 
  <input name="fName" type="text" id="fname" onkeyup="showFirstChar()">
</p>
<p>Initials: 

  <input name="Initials" type="text" id="Initials">    
  <script>
    function showFirstChar() {
        var sWord = document.getElementById('fName').innerHTML;
        document.getElementById('Initials').innerHTML = sWord.charAt(0);
    }
  </script>
  
</p>
</body>
</html>

Solution

  • try this

    var sWord = document.getElementById('fName').value;
    document.getElementById('Initials').value= sWord.charAt(0);
    

    Input has .value property instead of .textContent