开发者

HTML form with associated inputs

I've got a system where I allow a user to select multiple checkboxes from n amount of checkboxes, but also want two more inputs associated with each checkbox. This is for a message, a date and a time. Wh开发者_如何转开发en I post the data to be processed by a PHP script, I'd like to be able to access each of the sets of checkbox and two other inputs so I can see what date and time a user has filled in for each of the messages they've selected. I'm having trouble coming up with a method to associate the two other inputs with each checkbox.

Any ideas how to do this?


You can use arrays in your html inputs like so...

<input type="text" name="messages[1][message]" value="herp" />
<input type="text" name="messages[1][date]" value="24th April" />
<input type="text" name="messages[1][time]" value="13:00" />

<input type="text" name="messages[2][message]" value="derp" />
<input type="text" name="messages[2][date]" value="26th April" />
<input type="text" name="messages[2][time]" value="18:00" />


<?php

    $messages = $_REQUEST['messages'];
    foreach ($messages as $messageId => $value){
        echo $value['message'];
        echo $value['date'];
        echo $value['time'];
    }


Your HTML:

<input type="checkbox" name="car" />
<input type="text" name="msg_car" value="Car message" />
<input type="text" name="date_car" value="Car date" />

<input type="checkbox" name="bike" />
<input type="text" name="msg_bike" value="Bike message" />
<input type="text" name="date_bike" value="Bike date" />

<input type="checkbox" name="train" />
<input type="text" name="msg_train" value="Train message" />
<input type="text" name="date_train" value="Train date" />

<input type="checkbox" name="plane" />
<input type="text" name="msg_plane" value="Plane message" />
<input type="text" name="date_plane" value="Plane date" />

Your PHP script:

$array = array("car", "bike", "train", "plane");

for ($i = 0; $i < count($array); $i++) {
    if (isset($_POST[$array[$i]])) {
         //Checkbox was checked, get values
         $msg  = "";
         $date = "";

         $msg_id  = "msg_" . $array[$i];
         $date_id = "date_" . $array[$i];

         if (isset($_POST[$msg_id]))
              $msg  = $_POST[$msg_id];
         if (isset($_POST[$date_id]))
              $date = $_POST[$date_id];

    }
}

I think something like this should work. I didn't test it.. So forgive me if this example still contains some minor errors.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜