简体   繁体   中英

Why text input field disappearing (html , php)?

------------code 1 ------------

<!DOCTYPE html>
<html>
<body>
    <form action="#" method="POST">
        <input type ="text" value="default text" name="someName">
        <input type ="submit" value ="Submit" > 
    </form>
    <?php echo "Entered data is -->".$_POST["someName"]; ?> 
</body>
</html> 

----------------- code 2 ------------------

<?php 
echo $htmlDoc = <<< HTML
<html>
<body>
    <input type="button" value="Add Input Field"  onClick="addField();">
    <p id="addHere"></p>
</body>
</html> 
HTML;

echo ' Entered Data is as :  '.$_POST["someName"]; 
?>
<script>
    function addField()
    {
        document.getElementById("addHere").innerHTML
        ='<form action="#" method="POST">'+
         '<input type ="text" value="default text" name="someName">'+
         '<input type ="submit" value ="Submit" >'+ 
         '</form>';
   }
</script>

code1 works fine but in code2 after submit text input field disappears why? how to retain it and retain value entered in it?

that's because your form is not by default part of your DOM document.

you are appending your form using Javascript into your DOM document using a specific event onClick="addField();" .

and while Form Submission is a process that sends a POST/GET data to the server -Server Side Process- then the server return back with some data - refreshes the page -, so all your DOM changes will be forgotten or restarted so to speak after this submit .

So, to work around this, you may set your form as a part of your DOM document, and control the viability by javascript.

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