Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

select - Set default option with raw php variable (no javascript or other lib)

Hi I am trying to make dropdown with default set based on php variable but not getting desired result please help I am a new into this

<?php
if ($_POST['search'] != '') {
                $searchType = $_POST['search_type'];

}
?>
 <form action="" method="POST">
 <select name="search_type" id="search_type">
                        
                        <option value='A'    <?=(isset($searchType) && ($searchType=="A"))?'selected':'';?>    >A</option>
                        <option value='1'     <?=(isset($searchType) && ($searchType=="1"))??'selected';?>     >1</option>
                        <option value='x'   <?=(isset($searchType) && ($searchType=="x"))??'selected';?>     >x</option>
                        <option value='y' <?php (isset($searchType) && ($searchType=="y"))??'selected';?>    >y</option>
                        <option value='z' <?=(isset($searchType) && ($searchType=="z"))??'selected';?>     >z</option>
                       
                    </select>
<input type="text" name="search" id="search" placeholder="Search.. " >
</form>
question from:https://stackoverflow.com/questions/66057691/set-default-option-with-raw-php-variable-no-javascript-or-other-lib

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can save a bunch of code by creating an array of your values and looping through them. When looping through them, you can do a check if your value matches your POST data.

arr = ['A','1','x','y','z'];

foreach ($arr as $val){
    if($searchType === $val){
        $sel = 'selected';
    } else { $sel = '';};
    echo "<option value="".$val."" ".$sel.">".$val."</option>";
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...