简体   繁体   中英

show input field value in div using javascript

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.

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>

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM