1

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?

2
  • 1
    Could you provide a jsfiddle? Commented Dec 16, 2013 at 9:35
  • jsfiddle.net/ehx6M Here it is Commented Dec 17, 2013 at 0:20

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I get the idea. Now, I want to know how to get the max number of array [] or what was the last number inside []. So I can compare with the for loop. Thanks
It's okay now. I used end($quant_values); $compare=key($quant_values); to get the last set of array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.