![](/img/trans.png)
[英]how to get a URL parameter and set the value of a select option on page load?
[英]How to choose a <select> option value automatically from an URL parameter?
我有 2 步表單,我將 URL 中的名字從第 1 步傳遞到第 2 步,但我不確定如何對select
字段執行相同的操作。 作為一個例子,我有這個:
在網址中:
?名字=鮑勃
表單字段:
<input type="text" id="firstname" name="firstname" value="<?php echo $_GET['firstname']; ?>" required>
有一個變量傳入選擇字段的 URL,它是:
&colortype=黑色+和+白色
但是 Select 選項如下所示:
<label for="colortype">Colors...</label>
<select id="colortype" name="colortype">
<option value="" selected disabled hidden>Select an option</option>
<option value="Purple and Yellow">Purple and Yellow</option>
<option value="Red and Blue">Red and Blue</option>
<option value="Black and White">Black and White</option>
</select>
我試過添加選項:
<option value="<?php echo $_GET['colortype']; ?>">
<?php echo $_GET['colortype']; ?>
</option>
但沒有運氣。 有沒有辦法自動選擇通過 URL 來的colortype
?
用這個
<label for="colortype">Colors...</label>
<select id="colortype" name="colortype">
<option <?php if ($_GET['colortype'] == '' ) echo 'selected' ; ?> value="" disabled hidden>Select an option</option>
<option <?php if ($_GET['colortype'] == 'Purple and Yellow' ) echo 'selected' ; ?> value="Purple and Yellow">Purple and Yellow</option>
<option <?php if ($_GET['colortype'] == 'Red and Blue' ) echo 'selected' ; ?> value="Red and Blue">Red and Blue</option>
<option <?php if ($_GET['colortype'] == 'Black and White' ) echo 'selected' ; ?> value="Black and White">Black and White</option>
</select>
<label for="colortype">Colors...</label>
<select id="colortype" name="colortype">
<?php $color = $_GET['colortype']; ?>
<option <?php if ($color == '' ) { ?> selected="selected" <?php } ?> value="" >Select an option</option>
<option <?php if ($color == 'Purple and Yellow' ) { ?> selected="selected" <?php } ?> value="Purple and Yellow" >Select an option</option>
<option <?php if ($color == 'Red and Blue' ) { ?> selected="selected" <?php } ?> value="Red and Blue" >Select an option</option>
<option <?php if ($color == 'Black and White' ) { ?> selected="selected" <?php } ?> value="Black and White" >Select an option</option>
你可以試試這個代碼
顏色...
<option value="" selected disabled hidden>Select an option</option>
<option value="1">Purple and Yellow</option>
<option value="2">Red and Blue</option>
<option value="3">Black and White</option>
value="Black and White">黑色和白色
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.