Keshia Angelina Keshia Angelina - 1 year ago 64
HTML Question

Set Selected Value Based On Database Fetched Value

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 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>

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.

Answer Source

You can change your code thus:

<select name='slPayment'>
    <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>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download