Set Selected Value Based On Database Fetched Value

只愿长相守 提交于 2019-12-12 00:57:03

问题


Case :

Hi, Stackoverflow community.

I want to set selected value on SELECT type input based on fetched value from database table column. So if db table column contain "A", SELECT type input will also show "A".

Value in SELECT type input, provide manually.

Experiment :

To show my logic on how to do this, i tried this code

// $query2['via'] will produce fetched value from database
<select selected='".$query2['via']."' name='slPayment'>
<option>--</option>
<option value='Cash'>Cash</option>
<option value='Bank Transfer'>Bank Transfer</option>
<option value='Credit Card'>Credit Card</option>
<option value='Cheque'>Cheque</option>
<option value='Others'>Others</option>
</select>

Experiment Result :

Wont Work

Desired Output :

I actually just want that SELECT type input, show the exactly same value from fetched database value. Any idea how to fix this ?

Thank You

Thank you for Stackoverflow community. I won't stop saying thank you. Btw, i purely asking for learning and knowledge sharing. I'm open to any comment (related info with this question).

But please don't judge me like i am just asking for code. I actually learn how to code based on that code itself, then i adapt to make use of that code properly, am not familiar with library, am still a college student. I wont ask before i try it by myself. Some people did judge me on recent question. And it's not very nice act to this community. I'm learning, we learning.

So thank you once again.


回答1:


You can change your code thus:

<select name='slPayment'>
    <option>--</option>
    <option " . (($query2['via']=='Cash') ? 'selected="selected"': '') .  "value='Cash'>Cash</option>
    <option " . (($query2['via']=='Bank Transfer') ? 'selected="selected"': '') . " value='Bank Transfer'>Bank Transfer</option>
    <option " . (($query2['via']=='Credit Card') ? 'selected="selected"': '') . " value='Credit Card'>Credit Card</option>
    <option " . (($query2['via']=='Cheque') ? 'selected="selected"': '') . " value='Cheque'>Cheque</option>
    <option " . (($query2['via']=='Others') ? 'selected="selected"': '') . " value='Others'>Others</option>
</select>



回答2:


img_type is my query result and i want img_name in drop_down

 <select id="id_name"  name="photo_type" value="">
                  <option value=""></option>
                   <?php foreach($img_types as $row){ ?>
                    <option value="<?php echo $row->imgtype_id?>"><?php echo $row->imgtype_name?></option>
                    <?php } ?>
                </select>


来源:https://stackoverflow.com/questions/38651772/set-selected-value-based-on-database-fetched-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!