Jump to content

Checkbox to Dropdown Conversion?


natasha_thomas

Recommended Posts

Friends,

 

I have a Checkbox codes for Categories:

 

<?php 

  $categories = get_categories( 'orderby=name&hierarchical=0&hide_empty=0' );

  $n = 1;

  foreach ( $categories as $cat ): ?>

  <input type="checkbox" name="postcats[]" value="<?php echo $cat->cat_ID; ?>" >

    <?php 

echo $cat->cat_name; 

  $n = $n +1;
endforeach; ?><input type="hidden" name="abb_num_cats" value="<?php echo $n;?>">

 

Observe, the Checked categories are stored in $postcats[].

 

The Dropdown equivalent of Checkbox code is:

 

 

<select name="postcats">
<?php
$categories = get_categories( 'orderby=name&hierarchical=0&hide_empty=0' );
  	$n = 1;
    foreach ( $categories as $cat ):
$cat_id = $cat->cat_ID;

?>

<option name="postcats[]" value="<?php echo $cat_id;?>" <?php if ($cat_id==$amaniche_main_category){echo "selected";}?>>

<?php
echo $cat->cat_name;
?>
</option>
<?php
    $n = $n +1;
    endforeach; ?>

</select>

 

 

 

My Question is: In the Dropdown codes, how to Store selected option values in Array $postcats[].

 

Can someone help me out.

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/194409-checkbox-to-dropdown-conversion/
Share on other sites

You need to name your dropdown (<select>) as  "postcats[]" not your <option> tag. Only the <option> tag should have the value set. Also if you're going to allow users to select multiple items from the drop down you'll want to add multiple="multiple" to your select tag. Your corrected code

<select name="postcats[]" multiple="multiple">
<?php
$categories = get_categories( 'orderby=name&hierarchical=0&hide_empty=0' );
  	$n = 1;
    foreach ( $categories as $cat ):
$cat_id = $cat->cat_ID;

?>

<option value="<?php echo $cat_id;?>" <?php if ($cat_id==$amaniche_main_category){echo 'selected="selected"';}?>>

<?php
echo $cat->cat_name;
?>
</option>
<?php
    $n = $n +1;
    endforeach; ?>

</select>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.