Clicking a button to populate a div with value, and then use this value for an onclick function - Javascript

I have a text box here which when I click into it and press a letter, it populates with that letter. Then I click a button (Go) which takes the letter I have entered and runs a JavaScript function that works. This is the code:

<div id="enterlettertext">
  Enter the letter:&nbsp;
  <input type="text" id="myletterInput" name="myletterInput" />
</div>
<input type="button" id="wadgo" value="Go" 
   onclick="QuizAnswer(document.getElementById('myletterInput').value)">

Rather than clicking into the text box to enter a letter, I want to build an onscreen keyboard where the user presses the button representing the letter and this letter populates the text box. The user would then click ‘Go’ to run the function.

I built the following as the keyboard:

<button class="fiveninebutton" onclick="setLetter('q');">Q</button>
<button class="fiveninebutton" onclick="setLetter('w');">W</button>
<button class="fiveninebutton" onclick="setLetter('e');">E</button>
<button class="fiveninebutton" onclick="setLetter('r');">R</button>

And have this code:

function setLetter(letter) {
  document.getElementById('myletterInput').innerHTML =    
  document.getElementById('myletterInput').innerHTML + letter;
}

When I click the letter button, nothing happens. However, if I change:

<input type="text" id="myletterInput" name="myletterInput" /> 

to:

<div id="myletterInput" name="myletterInput"></div>

the letter is populated in the div just as I want it to - but the ‘go’ button function no longer works.

How do I get the letter to populate the div and then the other function which uses this button to work?

Understanding the Issue and Solution

The problem arises because the innerHTML property is designed to replace the entire contents of an element. When you use it to append a letter to the existing content, it’s essentially overwriting the previous content. This is why the ‘go’ button function stops working when you use a div .

Solution: Using value Property for input Elements

For input elements, the correct way to set and retrieve the value is to use the value property. This property specifically holds the text that the user has entered into the input field.

Here’s the corrected setLetter function:

JavaScript

function setLetter(letter) {
  document.getElementById('myletterInput').value += letter;
}

Explanation:

  • += operator appends the letter to the existing value of the input element.
  • This ensures that the previous content is preserved while adding the new letter.

With this change, you should be able to click the letter buttons, see the letters populate in the input field, and then click ‘Go’ to trigger the QuizAnswer function.

Remember to keep the input element with the type="text" attribute. Using a div for this purpose might not provide the expected behavior for input fields.