Michael Poxon
Michael Poxon

Reputation: 13

how can I get a database result to highlight at item in a selection list using PHP?

I would like to highlight an option in a select list based on the database result, also to check a radio button likewise.

I have seen lots of examples that go the other way (i.e., send the user's selected option to the DB - I have done this, no problem of course) but is it possible to do the reverse?

The selection list is already built, and works. I also have 2 radio buttons, just for yes and no. Again, the selected radio button sends the result to the DB no problem (values are either 1 or 0).

So... say that the user has picked 'Norfolk' from the option list and that is stored in the DB. I would like to retrieve that and then make 'Norfolk' the highlighted option when he returns to the form (say, to update his details)

Upvotes: 0

Views: 89

Answers (2)

Michael Poxon
Michael Poxon

Reputation: 13

I thought it should be simple and it was (just like me! ;-) ) This worked, so I'll post it in case anyone else is stuck on something similar...

<option selected="<?php echo $myregion; ?>"><?php echo $myregion;?></option>

...and that's it! Thanks however to everyone who helped.

Upvotes: 1

Ken Lee
Ken Lee

Reputation: 8093

For select box

<select name=test id=test>
<option value=1 <?php if ($c["test"]=="1") {echo " selected "; } ?>>1
<option value=2 <?php if ($c["test"]=="2") {echo " selected "; } ?>>2
<option value=3 <?php if ($c["test"]=="3") {echo " selected "; } ?>>3
</select>

For radio button

    <input type="radio" name="gender" value="male"  <?php if ($c["gender"]=="male") {echo " checked "; } ?>>
<br>
    <input type="radio" name="gender" value="female"  <?php if ($c["gender"]=="female") {echo " checked "; } ?>>

[Alternative Solution] : you may use the following to set the selected option /radio using the functions selectElement and setradio :

<form name="formx">
<select name=test id=test>
<option value=1 >1
<option value=2 >2
<option value=3 >3
</select>
<br><br>
<input type=radio name=test2 value="A">A
<br><br>
<input type=radio name=test2 value="B">B
</form>

<script>

function selectElement(id, valueToSelect) {    
    let element = document.getElementById(id);
    element.value = valueToSelect;
}


function setradio(xname,var2) {
var radios = document.formx.elements[xname];
index=0;
while (index < radios.length) {
if (radios[index].value == var2) {
radios[index].checked=true;
}index++;
}}


selectElement("test","2");
setradio("test2","B");




</script>

Upvotes: 0

Related Questions