Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with dynamic number of form input using PHP?

Tags:

javascript

php

Hi i have a form where user can select start date and end date of a leave. For example when the no of days is 3, there will be 3 row of date generated. Each date,day and period (am/pm) will be stored in the hidden field. So 3 days will generate a hidden field with name date_1, day_1, period_1, date_2, day_2, period_2, date_3, day_3, period_3.

The question is how to deal with this dynamic number of form input? I need to pass the value to the controller and then to model to store into database. This is the main problem since form input is number is dynamic and we need to pass it to the controller function.

Can someone show me the correct way of dealing with this problem? A link of tutorial will be helpful thanks :)

This is the code that is use to generate the list of date as in the picture below

function test(){
            var count = 0;
            var date1 = $('#alternatestartdate').val();
            var date2 = $('#alternateenddate').val();
            var startDate = new Date(date1);
            var endDate = new Date(date2);
            var Weekday = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
            while (startDate<=endDate)
            {
            var weekDay = startDate.getDay();
            if (weekDay < 6 && weekDay > 0) {
            var month = startDate.getMonth()+1;
            if( month <= 9 ) { month = "0"+month; }
            var day = startDate.getDate();
            var datearr = new Array();
            if( day <= 9 ) { day = "0"+day; }
            count++;
            var datelist = day+"-"+month+"-"+startDate.getFullYear();
            $('#pa').append(day+"-"+month+"-"+startDate.getFullYear() + " ("+Weekday[weekDay]+") <input type='hidden' id='' name='date_"+count+"' value='"+datelist+"' /><input type='hidden' id='' name='day_"+count+"' value='"+Weekday[weekDay]+"' /><input type='radio' name='period_"+count+"' value='1' checked/>Full<input type='radio' name='period_"+count+"' value='2'/>Half (AM)<input type='radio' name='period_"+count+"' value='3'/>Half (PM)<br />");

            }
            startDate.setDate(startDate.getDate()+1)
            }
            $('#pa').append("<input type='hidden' id='' name='countval' value='"+count+"' />");
        }

alt text

If insert correctly, the data the in database will look like this:

alt text

like image 719
cyberfly Avatar asked Sep 05 '10 16:09

cyberfly


1 Answers

If you put empty brackets at the end of the name attribute of all related tags, like so:

<input type='hidden' name='blah[]' value='foo' />
<input type='hidden' name='blah[]' value='bar' />

then they will be sent through the $_POST array as an array.

So you access them like this:

<?php

echo($_POST['blah'][0]); // foo
echo($_POST['blah'][1]); // bar

?>
like image 59
Brian Ortiz Avatar answered Sep 24 '22 18:09

Brian Ortiz