Abdulla
Abdulla

Reputation: 1127

POST Specific Textfields

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.

Upvotes: 0

Views: 50

Answers (4)

cwallenpoole
cwallenpoole

Reputation: 82058

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 ];
}

Upvotes: 1

Josh
Josh

Reputation: 6473

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.

Upvotes: 0

Philip
Philip

Reputation: 694

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.

Upvotes: 0

Ruslan Polutsygan
Ruslan Polutsygan

Reputation: 4461

You may handle the submit-event and remove unnecessary textareas from DOM using Javascript according to selected checkboxes before submit.

Upvotes: 0

Related Questions