Welcome Guest, Not a member yet? Register   Sign In
How to create IF->ELSE with input->post() with checkbox array?
#1

Hi guys.

I have a form that has several checkbox with the same "name" attribute. I'm trying to do a conditional to know if any checkbox is checked or not, but I can not make it work. See how it is:


PHP Code:
// View (have foreach checkboxes with the name 'service[]', no other input/select/etc )
<input type "checkbox" name "service[]" value "$numeric_id">

// Controller
$item $this->input->post ('service'true);
if(
$item){ //Run only when submit the form
 
 if ($item == NULL) {
 
   // function if no checkbox is checked
 
   // return to the same page with redirect(current_url());
 
 }else{
 
  // function if at least one checkbox was marked
 
  // return to the same page with redirect(current_url());
 
 }
}else{
 
 //show the view with the checkboxes and submit form button


The problem is that when i don't select any checkbox the input->post("service") is not NULL, not as empty or equals "" (empty).


PHP Code:
if($item==NULLnot work
if($item==FALSEnot work
if($item=='') or if($item==' 'not work
if(empty($item)) not work
if(!isset($item)) not work
if(!is_array($item)) or (is_array($item)) not work
foreach($item as $key) or foreach($item as $key => $valuenot work 


Any idea what's wrong?
Reply
#2

(This post was last modified: 09-23-2016, 05:08 AM by Wouter60.)

PHP Code:
if($item){ //Run only when submit the form
 
 if ($item == NULL) { 

This will never work. If you haven't selected any checkbox, $item will be empty, so the line with "if ($item == NULL) {" will not be executed.
I assume that your form has a submit button, probably with the name "submit".
PHP Code:
$submit $this->input->post('submit');
if (
$submit) {
 
 $items $this->input->post('service');
 
 if (! empty($items)) {
 
   foreach($items as $item) {
 
       //process the checkboxes that where checked
 
   }
 
 }
 
 else {
 
     // redirect
 
 }


Reply
#3

(09-23-2016, 03:51 AM)Wouter60 Wrote:
PHP Code:
if($item){ //Run only when submit the form
 
 if ($item == NULL) { 

This will never work. If you haven't selected any checkbox, $item will be empty, so the line with "if ($item == NULL) {" will not be executed.
I assume that your form has a submit button, probably with the name "submit".
PHP Code:
$submit $this->input->post('submit');
if (
$submit) {
 
 $items $this->input->post('service');
 
 if (! empty($items)) {
 
   foreach($items as $item) {
 
       //process the checkboxes that where checked
 
   }
 
 }
 
 else {
 
     // redirect
 
 }



Thanks man, this work fine to me. Big Grin
Reply




Theme © iAndrew 2016 - Forum software by © MyBB