1

I have a button, when I click on it a form is shown, It has and input field name, I am trying to display input field value in a another div after submitting the form. But I am unable to do it. What I am doing wrong?.

<!DOCTYPE html>
<html>
  <head>
   <script>
        function showDiv() {
            document.getElementById('hello').style.display = "block";
        }
        function showValue(){
            var name = document.getElementById('name').value;
            document.getElementById('ans').innerHTML = name;
        }
   </script>
  </head>
  <body>
    <input type="button" onclick="showDiv()" value="click on me"/>  
    <form id="hello"  style="display:none;">
        <label>Enter Name: </label><br>
        <input type="text" id="name" required>
        <input type="submit" value="submit" onclick="showValue()">
    </form>
    <div id="ans"></div>
  </body>
</html>

Please help me, thanks In advance.

2 Answers 2

3

The value actually appears in the div but your form submits immediately. One way to get away is to not use submit button. Change input[type=submit] to button[type=button].

This will prevent the form from being submitted.

function showDiv() {
  document.getElementById('hello').style.display = "block";
}

function showValue() {
  var name = document.getElementById('name').value;
  document.getElementById('ans').innerHTML = name;
  document.getElementById('hello').style.display = "none";
}
<input type="button" onclick="showDiv()" value="click on me" />
<form id="hello" style="display:none;">
  <label>Enter Name: </label><br>
  <input type="text" id="name" required>
  <button type="button" onclick="showValue()">submit</button>
</form>
<div id="ans"></div>

Sign up to request clarification or add additional context in comments.

3 Comments

Sir I want to hide the form after submit, only want to show the value of input. how to do this ?
@JamieSouthwell -- Glad to help. Please accept this answer if it helped you.
@JamieSouthwell -- please see this post. It will guide you on upvoting/accepting answers.
1

function showDiv() {
  document.getElementById('hello').style.display = "block";
}

function showValue() {
  var name = document.getElementById('name').value;
  document.getElementById('ans').innerHTML = name;
  document.getElementById('hello').style.display = "none";
}
<input type="button" onclick="showDiv()" value="click on me" />
<form id="hello" style="display:none;">
  <label>Enter Name: </label><br>
  <input type="text" id="name" required>
  <button type="button" onclick="showValue()">submit</button>
</form>
<div id="ans"></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.