I've got a set of dynamically generated checkboxes and a textarea input for each checkbox. I want to 开发者_开发百科send the values of the textareas via POST of checked checkboxes only. How is this possible?
I can send seperate arrays of both the checkboxes and textareas, but the checkboxes only store values for checked items so it is very difficult to tell which textarea goes with which checkbox.
It actually isn't hard:
foreach( $inputs as $key => $value )
{
?>
<input type="checkbox" name="cb[<?php echo $key ?>]" />
<input type="text" name="tf[<?php echo $key ?>]" value="<?php echo $value ?>" />
<?php
}
Now, in the receiver of the POST:
foreach( $_POST[ 'cb' ] as $key => $value )
{
// this is the value of a textfield which has a corresponding cb checked,
$text = $_POST[ 'tb' ][ $key ];
}
You may handle the submit-event and remove unnecessary textareas from DOM using Javascript according to selected checkboxes before submit.
You could do something with Javascript, for instance delete the unwanted textareas when the user clicks Submit, but that's a dirty way to do it for something simple. It's best not to rely on Javascript for validating and processing input.
The better approach in my opinion is to process the POST array in PHP. It seems the trouble is that the checkboxes are not named properly so they can't be matched with the textareas. The solution to that is to come up with a better naming scheme, which should be straightforward.
You cannot do that. I think what you are trying to do is only process the textarea's that have a corresponding checked box. A simple way to do this is to name the checkbox's an textarea's such that they create an array, where the index ties them togethor.
For example:
<textarea name="boxes[0][text]"></textarea><input type="checkbox" name="boxes[0][checked]">
<textarea name="boxes[1][text]"></textarea><input type="checkbox" name="boxes[1][checked]">
Then when you process the POST data you need but foreach
through the array with an if
clause if the ["checked"] element is set.
精彩评论