简体   繁体   中英

Default no selection for HTML <select> that is created in a for loop

My HTML select statement is:

<p>Height w/o shoes between (inches)</p>
<select name="woShoes">
<?php for ($i = 1; $i < 300; $i++) {?>
<option value="<?php echo $i;?>"><?php echo $i; ?></option>
<?php } ?>
</select> And
<select name="woShoes2">
<?php for ($i = 1; $i < 300; $i++) {?>
<option value="<?php echo $i;?>"><?php echo $i; ?></option>
<?php } ?>
</select>

But I want to add a default no selection since I am checking if the statement is selected or not, right now it's always 1 so it's processed as selected even though that is the default.

The way I check if it's empty is

if (!empty($_POST['woShoes']) && !empty($_POST['woShoes2'])) {

how can I add a default no selection select when I generate the values in a for loop?

Just add empty option before your for loop, like this:

<p>Height w/o shoes between (inches)</p>
<select name="woShoes">
<option></option>
<?php for ($i = 1; $i < 300; $i++) {?>
<option value="<?php echo $i;?>"><?php echo $i; ?></option>
<?php } ?>
</select> And
<select name="woShoes2">
<option></option>
<?php for ($i = 1; $i < 300; $i++) {?>
<option value="<?php echo $i;?>"><?php echo $i; ?></option>
<?php } ?>
</select>
<p>Height w/o shoes between (inches)</p>
<select name="woShoes">
<option selected="selected"></option>
<?php for ($i = 1; $i < 300; $i++) {?>
<option value="<?php echo $i;?>"><?php echo $i; ?></option>
<?php } ?>
</select> And
<select name="woShoes2">
<option selected="selected"></option>
<?php for ($i = 1; $i < 300; $i++) {?>
<option value="<?php echo $i;?>"><?php echo $i; ?></option>
<?php } ?>
</select>

You can have something like above where you put an empty selected value. For more about select attribute check here

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