简体   繁体   中英

How to set the default value of a dropdown on multiple pages to different selections

I have a complex dropdown form that's being called on multiple pages. However, on those various pages I would like a different default value to appear.

If the code for the dropdown is located in one source file then what code could I write in the various pages to set that default value according to what I want for each respective page?

Because the form is complex it's hard to write in as an example. So here's something basic to work from:

https://jsfiddle.net/8jb3xdbo/

<select id="my_select">
    <option value="a">a</option>
    <option value="b">b</option>
    <option value="c">c</option>
</select>

If that function is being called on 3 different pages then how would I approach adding code to each page that would set the default value as "a" on one, "b" as another, and "c" as another.

Before you include the file

$default = 'a'; //OR 'b' or whatever you want
include('dropdown.php');

In your dropdown.php

<?php

$default = !empty($default) ? $default : 'a';
<select id="my_select">
    <option value="a" <?php echo $default=='a' ? 'selected' : ''; ?>>a</option>
    <option value="b" <?php echo $default=='b' ? 'selected' : ''; ?>>b</option>
    <option value="c" <?php echo $default=='c' ? 'selected' : ''; ?>>c</option>
</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