1

I make a calculator on my website. But I encountered a problem. When the text is wider than the input width, the text is added correctly, but we can't see it. Note that when we do not press a button but enter it from the keyboard, it works, but I need to press them.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
    <!--CSS3-->
    <style>
        #result {
            width: 100px;
            height: 40px;
            font-size: large;
        }
    </style>

    <!--HTML5-->
    <input type="text" id="result">
    <button id="addSeven">7</button>
    <button id="addEight">8</button>

    <!--JavaScript-->
    <script>
        var result = document.getElementById("result");
        var button7 = document.getElementById("addSeven");
        var button8 = document.getElementById("addEight");

        button7.onclick = function() {
            result.value += "7";
        }
        button8.onclick = function() {
            result.value += "8";
        }

    </script>

</body>
</html>
terrymorse
  • 6,771
  • 1
  • 21
  • 27
Horki
  • 39
  • 7
  • 4
    Your question title shouldn't be a scenario the leads up to a problem, it should be a short statement of the problem itself. What actual problem are you having? – Scott Marcus May 12 '20 at 19:34
  • 1
    It is also unclear from your main question's text what should happen and what is incorrectly happening now. Please edit your question and take the time to clearly explain what should happen and what is wrong with what is happening now. * it appears, but we can't see it* doesn't make any sense. If it appears, then you can see it. – Scott Marcus May 12 '20 at 19:38

1 Answers1

3

An option is to use .focus() after every entry:

var result = document.getElementById("result");
var button7 = document.getElementById("addSeven");
var button8 = document.getElementById("addEight");

button7.onclick = function() {
  result.value += "7";
  result.focus();
}
button8.onclick = function() {
  result.value += "8";
  result.focus();
}
#result {
  width: 100px;
  height: 40px;
  font-size: large;
}
<input type="text" id="result">
<button id="addSeven">7</button>
<button id="addEight">8</button>

Update

If you want the text to stay on the end after lost the focus, you can set the scrollLeft property to the end of the input:

var result = document.getElementById("result");
var button7 = document.getElementById("addSeven");
var button8 = document.getElementById("addEight");

button7.onclick = function() {
  result.value += "7";
  result.scrollLeft = result.scrollWidth;
}
button8.onclick = function() {
  result.value += "8";
  result.scrollLeft = result.scrollWidth;
}
#result {
  width: 100px;
  height: 40px;
  font-size: large;
}
<input type="text" id="result">
<button id="addSeven">7</button>
<button id="addEight">8</button>
Tamas Szoke
  • 5,426
  • 4
  • 24
  • 39