How to checkbox checkbox fields dynamically with PHP? [duplicate]

-1

I'm sending neighborhoods through $ _GET through a form and would like to dynamically mark them in the screen update thus making a system persistence of the results sought.

<fieldset class="normal">
    <input type="checkbox" name="bairros[]" value="BELEM NOVO" id="BELEM NOVO">
    <label for="BELEM NOVO">Belém Novo</label>  
    <input type="checkbox" name="bairros[]" value="BOM FIM" id="BOM FIM">
    <label for="BOM FIM">Bom Fim</label>
    <input type="checkbox" name="bairros[]" value="SANTA CLARA" id="SANTA CLARA">
    <label for="SANTA CLARA">Santa Clara</label>
</fieldset>

I include the file bairros.php shortly after body with require and capture all neighborhoods that were marked on the form with $ _GET on page return.

# Persistencia dos bairros
$inbairros = $_GET["bairros"];
if(array_key_exists("bairros", $_GET)){     
    foreach($inbairros as $baitem => $bavalue) {
        // select bairros       
    }   
}

If I do echo $bavalue within foreach , logically it returns me all neighborhoods that were selected on the form. The value of the input contains the same content.

    
asked by anonymous 05.11.2014 / 04:29

1 answer

1

Boy ... What a confusing question ...

First, this here:

$inbairros = $_GET["bairros"];
if(array_key_exists("bairros", $_GET)){     
    foreach($inbairros as $baitem => $bavalue) {
        // select bairros       
    }   
}

It should be at least:

$bairros = ( array_key_exists( 'bairros', $_GET ) ? $_GET['bairros'] : array() );

foreach( $bairros as $bairro ) {

    // Faz alguma coisa
}

But that still does not solve your problem. To solve it we should know how this foreach relates to the HTML itself.

Normally something like this is done:

// Apenas um exemplo, isso viria do banco

$bairros = array( 'bairro1', 'bairro2', 'bairro3', 'bairro4', 'bairro5' );

foreach( $bairros as $bairro ) {
    echo '<input type="checkbox" name="bairros[]" value="' . $bairro . '" id="' . $bairro . '">';
    echo '<label for="' . $bairro . '">' . $bairro . '</label> ';
}

And to persist the checked checkboxes, something like this:

// Apenas um exemplo, isso viria do banco

$bairros = array( 'bairro1', 'bairro2', 'bairro3', 'bairro4', 'bairro5' );

// Apenas um exemplo, isso seria o $_GET

$bairrosSelecionados = array( 'bairro3', 'bairro4' );

foreach( $bairros as $bairro ) {

    $checked = ( in_array( $bairro, $bairrosSelecionados ) ? ' checked="checked" ' : ' ' );

    echo '<input type="checkbox" name="bairros[]"' . $checked . 'value="' . $bairro . '" id="' . $bairro . '">';
    echo '<label for="' . $bairro . '">' . $bairro . '</label> ';
}

Read, understand and adapt to your needs. ;)

    
05.11.2014 / 14:49