0

My checkboxes look like this

<div>
    <input type="checkbox" name="fruits[]" value="apple" <?php echo set_checkbox('fruits[]', 'apple'); ?> />
    <input type="checkbox" name="fruits[]" value="banana" <?php echo set_checkbox('fruits[]', 'banana'); ?> />
    <input type="checkbox" name="fruits[]" value="peach" <?php echo set_checkbox('fruits[]', 'peach'); ?> />
</div>

I am using array in the names so that I can populate a text field (via jquery) with the values of the checkboxes I select. I am using a script found on stackoverflow.

function calculate() {

        var fruit = $.map($('input:checkbox:checked'), function(e, i) {
            return e.value;
        });

        $('#fruits').val(fruit.join(',')); //adds values separated by comma to #fruits input 
    }

    calculate();

    $('div').delegate('input:checkbox', 'click', calculate);

So far it works but I'm having trouble setting validation rules for the checkboxes because they all have the same name. I tried..

$this->form_validation->set_rules('fruits[]', 'Apple', 'required|xss_clean');
$this->form_validation->set_rules('fruits[]', 'Banana', 'required|xss_clean');
$this->form_validation->set_rules('fruits[]', 'Peach', 'required|xss_clean');

and used echo form_error('fruits[]'); to display validation error but nothing happens. Ultimately I want to display a checkbox in the state it was submitted, should an error occur on another field in my form. Instead all the checkboxes uncheck. I'm not sure how to fix this.

POST

Array ( [FRUITS] => Array ( [0] => apple [1] => banana [2] => peach )

this is when they are checked

2
  • Can you give us your POST? Place this before form validation print_r($_POST); die(); Commented May 30, 2011 at 17:56
  • yes, have updated my question Commented May 30, 2011 at 18:02

1 Answer 1

2

Try without using the square brackets [], so just 'fruits'.

The [] are just to say to the browser "post these values as an array, not a single value, because they're a group", but in PHP you would just approach it as any other value, viz. $_POST['fruits'].

Hope that helps,

All the best, NwN

Sign up to request clarification or add additional context in comments.

3 Comments

To clarify, keep the brackets in the HTML, but loose them in: $this->form_validation->set_rules('fruits', 'Apple', 'required|xss_clean');
thanks! but without the brackets it doesn't work. I eventually added a loop.
actually the jquery seems to work with any name as long as its a checkbox. You may be right

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.