Home > Back-end >  How to display the value of a html user input using JavaScript when a button is clicked?
How to display the value of a html user input using JavaScript when a button is clicked?

Time:06-27

How to display the value of a html user input using JavaScript when a button is clicked? I've tried, but it gives "[object HTMLInputElement]" instead of the user entered value.

Here's code.

<body>
<p>8   7 = ....</p>
<input type="text" name="ans" id="ans1" placeholder="Enter your answer here">
<button type="button" onclick="Game()">OK</button>
<button type="button" onclick="Clear()">Cancel</button>
<br><br>

<h1>A Simple Math Game</h1>
<p>
    <strong>Question 1</strong>
    <span id="question1"></span>
    <span id="answer1"></span>
    <span id="feedback"></span>
</p>

<script>
    document.getElementById("question1").innerHTML= "8   7 = ...";
    function Game() {
        let user = document.getElementById("answer1").innerHTML= ans1;
    
    }
        
</script>

Here's the output I got.

8 7 = ....32 OK(button) Cancel(button)

A Simple Math Game Question 1 8 7 = ... [object HTMLInputElement] // this is the problem..!

CodePudding user response:

<body>
<p>8   7 = ....</p>
<input type="text" name="ans" id="ans1" placeholder="Enter your answer here">
<button type="button" onclick="Game()">OK</button>
<button type="button" onclick="Clear()">Cancel</button>
<br><br>

<h1>A Simple Math Game</h1>
<p>
    <strong>Question 1</strong>
    <span id="question1"></span>
    <span id="answer1"></span>
    <span id="feedback"></span>
</p>

<script>
    document.getElementById("question1").innerHTML= "8   7 = ...";
    function Game() {
        let user = document.getElementById("answer1").innerHTML= ans1;
    
    }
        
</script>

<body>
<p>8   7 = ....</p>
<input type="text" name="ans" id="ans1" placeholder="Enter your answer here">
<button type="button" onclick="Game()">OK</button>
<button type="button" onclick="Clear()">Cancel</button>
<br><br>

<h1>A Simple Math Game</h1>
<p>
    <strong>Question 1</strong>
    <span id="question1"></span>
    <span id="answer1"></span>
    <span id="feedback"></span>
</p>

<script>
    document.getElementById("question1").innerHTML= "8   7 = ...";
    function Game() {
        let user = document.getElementById("answer1").innerHTML= ans1.value;
    
    }
        
</script>

  • Related