0

Ive got whole bunch of checkbox inputs which all have same name attribute. I want to save their values (1 if checked, also 0 if not because order matters, I need to output them in right order) as an array which is not going as expected.

<input type="checkbox" name="feature[]" id="feature-a"/>
<input type="checkbox" name="feature[]" id="feature-b"/>
<input type="checkbox" name="feature[]" id="feature-c"/>
<input type="checkbox" name="feature[]" id="feature-d"/>

etc


foreach( $_POST['feature'] as $feature ) {

    if( isset( $feature ) && '' !== $feature ) {
        $feature = 1; 
    }
    else {
        $feature = '';
    } 

    $features = array();
    array_push($features, $feature);
}
update_term_meta( $term_id, 'features', $features );

//This always outputs a:1 {i:0;i:1;} for some reason! No matter what I check

What am I missing?

  1. I tried to add feature[] as name attribute
  2. I tried to assing '' or "" to $feature

Nothing is working. Is there a mistake in my loop I can't see?

Solo
  • 6,687
  • 7
  • 35
  • 67
  • 1) You need to apply `feature[]` as a `name` attribute. 2) As you were not applying any values to your checkboxes then when you select checkboxes it'll pass an array of `selected` checkboxes with a value of `Yes` and you'll not receive those values which aren't `checked` – Narendrasingh Sisodia Dec 16 '15 at 05:38
  • I updated my code, please have a look. – Solo Dec 16 '15 at 05:42
  • You won't get those values which are not checked – Narendrasingh Sisodia Dec 16 '15 at 05:43
  • Possible duplicate of [How get value for unchecked checkbox in checkbox elements when form posted?](http://stackoverflow.com/questions/19239536/how-get-value-for-unchecked-checkbox-in-checkbox-elements-when-form-posted) Also check [post the checkboxes that are unchecked](http://stackoverflow.com/questions/1809494/post-the-checkboxes-that-are-unchecked) – Narendrasingh Sisodia Dec 16 '15 at 05:44
  • So, there's no way to save checkboxes as an array with certain order? I mean situations where unchecked boxes also matter. Also, I ALWAYS get the same output as in code's comment, no matter what boxes I check, even if 10 checkboxes - still the same. – Solo Dec 16 '15 at 05:46
  • Please check my [previous comment](http://stackoverflow.com/questions/34304601/saving-several-checkbox-inputs-as-an-array?noredirect=1#comment56351344_34304601) for you first question. And for second one you need to post the values that you were getting within your `$_POST` method `checked` and `unchecked` – Narendrasingh Sisodia Dec 16 '15 at 05:48

1 Answers1

1

foreach( $_POST['feature'] as $feature ) {

if( isset( $feature ) && $feature !=='' ) {
    $feature = 1; 
}
else {
    $feature = 0;
} 

$features = array();
array_push($features, $feature);

} update_term_meta( $term_id, 'features', $features );