0

I used Javascript with PHP. In my HTML form it has a drop down(option) menu so that user can select the no. of authors. According to the number selected, dynamic input boxes will be displayed under names of authors. So here is my HTML form code.

<form method="post" action="" onsubmit="">
No. of Authors:<select id="steps_number" name="AuthorNo">
                  <option value="1" selected="selected" >1</option>
                  <option value="2">2</option>
                  <option value="3">3</option>
                  <option value="4">4</option>
                  <option value="5">5</option>
                </select><br/>
Author Names:<div id="inputBoxes"></div><br/>
<button type="submit" name="submit"></form>

My javascript code to display dynamic input text boxes according to author number selected is;

<script language="javascript">
    $(document).ready(function(){
        $("#steps_number").change(function() { 
            var inputNum = $("#steps_number").val();

            var inputCode = "";
            for(i=0; i<inputNum; i++) { 
                inputCode += "<p class=\"inputBox\"><input name='inp' id=\"inputBox_" + i + "\" size=\"20\" type=\"text\"></p>"
            }
            $("#inputBoxes").html(inputCode);
        });
    });
</script>

PHP code to get values when submitted is;

<?php
if(isset($_POST['submit'])) { 
$AuthorNo=strip_tags($_POST['AuthorNo']);
$AName=strip_tags($_POST['inp']);}

If the no of authors are selected as 2, two input text boxes will be displayed. If i submit it with two different values in each input box, only the value of 1st input box will be inserted to the database. Please tell me a way to name the input boxes in the loop differently and a way to call their values? Thank You.

1
  • 1
    name="inp[]" – that will get you an array. Commented Oct 8, 2013 at 12:27

1 Answer 1

1

The input can have a name like name=inpAuthor[] this will send an array to PHP.

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

3 Comments

If i give input name as name="inp[i]" and in php code; $AName=strip_tags($_POST['inp[i]']); it says undefined index: inp[i]
Use a foreach loop to access the values and do not use any value for the index. it should be just name=inp[]
It worked! Thank you very much. I changed my last code as follows; <?php if(isset($_POST['submit'])) { $AuthorNo=strip_tags($_POST['AuthorNo']); $AName=$_POST['inp']; foreach ($AName as $value){ echo "$value <br>";} } ?>

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.