开发者

Form submit handling and generating

I have this form that I need to submit few question with some hidden values 开发者_C百科and link them all together.

I currently append name with the ID of the question and then add _ then the number of answers.

<form>
    <span>1:Question goes here </span>
    <input type=hidden name=t_1 value=10>
    <input type=hidden name=f_1 value=20>
    <input type=checkbox name=a1_1>value1
    <input type=checkbox name=a1_2>value2
    <input type=checkbox name=a1_3>value3
    <span>2:Question goes here </span>
    <input type=hidden name=t_2 value=40>
    <input type=hidden name=f_2 value=20>
    <select name=a2_1>
        <option>blah</option>
        <option>etc</option>
    </select>
</form>

On the server side, I explode the fields submitted and put them together:

foreach ($_POST as $var => $val) {
    switch ($var[0]) {
        case "a" :
            $b = substr($var, 1); // remove first char to get number following
            $pos = strpos($b, "_");
            if ($pos !== false) {
                $i = explode("_", $b); // separating question number from choice number (for multi select questions)
                $answer[$i[0]][] = $val;
                break;
            }
            else {
                $answer[$b][] = $val;
                break;
            }
        case "t" :
            $b = substr($var, 1);
            $target[$b] = $val;
            break;
    }
}

Is there a better way to do this?


you can name your tags in the following manner:

<input name="question[1][answer]" type="text" value="someValue" />

this will create array for your questions and you can itterate through them, without needing to explode or substring anything.


You may use

f[] or f[1], f[2]

Doing so, $_POST will contain an array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜