Logan Wayne
Logan Wayne

Reputation: 5991

How to insert dynamically added text boxes into MySQL database

I used Javascript to dynamically add textbox in order for the user to add more items in one process. Here's the code that add textboxes:

<script type="text/javascript">

    var quantity = document.getElementById('quantity');
    var item = document.getElementById('item');
    var serial = document.getElementById('serial');
    var property = document.getElementById('property');

    document.getElementById('add').onclick = function () {
        var input = document.createElement('input'),
        div = document.createElement('div');
        input.type = "text";
        input.setAttribute("name", "quant");
        div.appendChild(input);
        quantity.appendChild(div);

        var input2 = document.createElement('input'),
        div2 = document.createElement('div');
        input2.type = "text";
        input2.setAttribute("name", "items");
        div.appendChild(input2);
        item.appendChild(div);

        var input3 = document.createElement('input'),
        div3 = document.createElement('div');
        input3.type = "text";
        input3.setAttribute("name", "serno");
        div.appendChild(input3);
        serial.appendChild(div);

        var input4 = document.createElement('input'),
        div4 = document.createElement('div');
        input4.type = "text";
        input4.setAttribute("name", "proper");
        div.appendChild(input4);
        property.appendChild(div);

    };

</script>


When the user clicks the "Add Text" button, one set (four textboxes) will appear. My problem is even if the user clicks and inputs data into those textbox, it will only insert one set of data (which was the last set of input). Its because of the "name" of the textbox are the same. How can I insert those multiple data? Or how can I set a unique name for the added textbox in order to insert them into the database?

Upvotes: 1

Views: 1666

Answers (1)

Samuel Liew
Samuel Liew

Reputation: 79022

You'll want to change the names with a [] appended to it. This will pass an array to the PHP on form submit.

input.setAttribute("name", "quant[]");

To get the values in PHP,

$quant_values = $_GET['quant']; // array of values 
$value_one = $quant_values[0];

You will need to implement a loop to iterate through the values.

Upvotes: 2

Related Questions