简体   繁体   中英

How to change drop-down box default value?

I am generating a drop-down box with PHP that has a value range of 0-30 in 1 step increments.

But how do I make the default value 1? I need the standard value that appears before the user changes the amount to be 1. At the moment the default value is 0.

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

global $product;

$defaults = array(
    'max_value'   => apply_filters( 'woocommerce_quantity_input_max', '', $product ),
    'min_value'   => apply_filters( 'woocommerce_quantity_input_min', '', $product ),
    'step'        => apply_filters( 'woocommerce_quantity_input_step', '1', $product ),
);

if ( ! empty( $defaults['min_value'] ) )
    $min = $defaults['min_value'];
else $min = 0;

if ( ! empty( $defaults['max_value'] ) )
    $max = $defaults['max_value'];
else $max = 30;

if ( ! empty( $defaults['step'] ) )
    $step = $defaults['step'];
else $step = 1;

?>
<div class="quantity_select">
    <select name="<?php echo esc_attr( $input_name ); ?>" title="<?php _ex( 'Qty', 'Product quantity input tooltip', 'woocommerce' ) ?>" class="qty">
    <?php
    for ( $count = $min; $count <= $max; $count = $count+$step ) {
        if ( $count == $input_value )
            $selected = ' selected';
        else $selected = '';
        echo '<option value="' . $count . '"' . $selected . '>' . $count . '</option>';
    }
    ?>
    </select>
</div>

If I am not mistaken $input_value is 1 or selected value. Then the below code work out.

for ( $count = $min; $count <= $max; $count = $count+$step ) {
        if ( $count == $input_value )
            $selected = ' selected="selected"';
        else $selected = '';
        echo '<option value="' . $count . '"' . $selected . '>' . $count . '</option>';
    }

Try the following:

<?php
echo "<select name=\"".esc_attr( $input_name )."\" title=\""._ex('Qty', 'Product quantity input tooltip', 'woocommerce').\"" class=\"qty\">";
for ($i = 1; $i <= 30; $i++) {
  echo "<option value=\"{$i}\"".(($i==1)?" selected":"").">{$i}</option>";
}
echo "</select>";
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM