Wednesday, March 20, 2019

Dynamic Form Data

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
</head>
<body>
<form method="POST" action="test.php">   
     <div id="dynamicInputsA">
        <span id="clone1">Pets<input type="text" name="myInputs[]"></span>
     </div>
     <input type="button" value="Add another text input" onClick="addInput('dynamicInputsA', 'clone1');">
     <input type="submit" value="test"/>
</form>    
<script>
    var counter = [];
    var limit = 3;
    function removeInput(divName, olddiv) {
        document.getElementById(divName).removeChild(olddiv);
        counter[divName]--;
    }
    function addInput(divName, clone){
         if (counter[divName] === undefined) {
             counter[divName] = 1;
         }
         if (counter[divName] == limit)  {
              alert("You have reached the limit of adding " + limit + " inputs");
         } else {
              var newdiv = document.createElement('div');
              var content = document.getElementById(clone).innerHTML;
              newdiv.innerHTML = content + "<button type='button' onClick='removeInput(\""+divName+"\", this.parentElement);'>Remove</button>";
              document.getElementById(divName).appendChild(newdiv);
              counter[divName]++;
         }
    }
</script>

</body>
</html>


Here is test.php:

    $myInputs = $_POST["myInputs"];

    foreach ($myInputs as $eachInput) {
         echo $eachInput . "<br>";
    }

No comments:

Post a Comment