Sujith Nair
Sujith Nair

Reputation: 97

Dynamically added field in javascript and saving the data to mysql

Iam having a small issues with my dynamic form in javascript. when i click add supplier button, two form fields are added automatically. i can add how much fields ever i wanted. But when i click add supplier button the previously added form values are going off. What's the mistake iam doing?

 <html>
<head>
    <script type="text/javascript">
        function addTextArea(){
            var div = document.getElementById('div_quotes');
            div.innerHTML += "<input type='text' name='sup_name[]' />";
            div.innerHTML += "<input type='text' name='sup_email[]' />";
            div.innerHTML += "\n<br />";
        }
    </script>
</head>
<body>
<form method="post" action="ajax.php?tender_id=<?php echo $tender_id ?>">
<div id="div_quotes"></div>
<input type="button" value="Add Supplers" onClick="addTextArea();">
<input type="submit" name="submitted">
</form>
</body>
</html>

Upvotes: 0

Views: 26

Answers (1)

Vibhesh Kaul
Vibhesh Kaul

Reputation: 2613

Use appendChild() instead of innerHTML that will prevent the existing form elements from getting overwritten.

function addTextArea(){
        var div = document.getElementById('div_quotes');
        var temp = document.createElement('div');
        temp.innerHTML ="<input type='text' name='sup_name[]' /><input type='text' name='sup_email[]' /><br />";
        div.appendChild(temp );
    }

Upvotes: 1

Related Questions