0

I want to use a form to do parametric filtering by passing values to a URI. Specifically, part of this form would entail multiple checkboxes for one parameter set, I'll call this 'my-checkbox-parameter'

What I Have

  • A basic form with checkbox fields that post the values via the GET method
  • This does correctly post the values as I'd expect

My code:

<form id="results-filters" class="form-inline" action="form.php"  method="GET">
    <div class="form-group">
        <label class="checkbox-inline">
            <input type="checkbox" id="val3" value="val1" name="my-checkbox-parameter[]" class="form-control">
            Value 1
        </label>
        <label class="checkbox-inline">
            <input type="checkbox" id="val2" value="val2" name="my-checkbox-parameter[]" class="form-control">
            Value 2
        </label>
        <label class="checkbox-inline">
            <input type="checkbox" id="val3" value="val3" name="my-checkbox-parameter[]" class="form-control">
            Value 3
        </label>
    </div>
    <button type="submit" class="btn btn-default">
        Filter Results
    </button>
</form>

What I'm Stuck on

  • Making the checkbox fields reflect 'checked' status based on what parameters are in the URL. For instance, if my URI is: /form.php?my-checkbox-parameter[]=val1&my-checkbox-parameter[]=val2 , how can I make sure that the field values for 'Value 1' and 'Value 2' are checked? Is JavaScript/AJAX the only way to do this?
  • Bonus points, not a super huge priority, but rather a 'nice to have'... Is there a better way to handle checkbox value arrays in URIs? For instance, if I have 10 checkbox fields, the concatenated URI with these parameters might be quite long...

Thanks in advance!

Ryan Dorn
  • 417
  • 7
  • 20

1 Answers1

2

First:

$checked= array();
$checked=$_GET['my-checkbox-parameter'];

And then:

<input type="checkbox" id="val1" value="val1" name="my-checkbox-parameter[]" class="form-control" <?php if(in_array("val1", $checked))echo "checked"; ?> >Value 1

So if there is val1 in your get parameters, the check box will be checked.

Do it for all check boxes and it should be ok.

AND for the second question: actually you are doing well with my-checkbox-parameter[ ], it's the usual way to do it in PHP. But you can check this question for more ways.

Community
  • 1
  • 1
wander
  • 208
  • 1
  • 15
  • Thanks wander, that works perfectly. I just modified things a bit to include the 'isset': `Value 1` Also thanks for that link, I'll check it out! – Ryan Dorn May 19 '16 at 12:35
  • Yeah that's a good idea. Make sure to accept my answer if it helped. Cheers – wander May 19 '16 at 12:52