简体   繁体   中英

How to set the default selected radio button in a group depending on a database value?

html:

<label><input type="radio" name="league" value="Bronze">Bronze</label>
<label><input type="radio" name="league" value="Silver">Silver</label>
<label><input type="radio" name="league" value="Gold">Gold</label>
<label><input type="radio" name="league" value="Platinum">Platinum</label>
<label><input type="radio" name="league" value="Diamond">Diamond</label>
<label><input type="radio" name="league" value="Master">Master</label>
<label><input type="radio" name="league" value="Grand Master">Grand Master</label>

I have a database column that will save the one they select as a VARCHAR (should I be using something else?). How do I set it up so that the radio button that lines up with what is stored in the database will be selected?

I may also just change this to a drop down menu, but I will still need to know how to set the selected value for that as well.

Here is what I have tried, but it doesn't seem to work for some reason.

<?php
     $leagues = array('Bronze', 'Silver', 'Gold', 'Platinum', 'Diamond', 'Master', 'Grand Master');
     foreach ($leagues as $key=>$value) {
          $selected = ($value == $user_data['league'] ? ' selected="selected"' :  '');
          echo '<label><input type="radio" name="league"' . $selected . ' value="' . $value . '">' . $value . '</label> ';
     }
?>

First, get the stored value from your db. What server-side language are you using?

Edit: added php.

<?php
 $leagues = array('Bronze', 'Silver', 'Gold', 'Platinum', 'Diamond', 'Master', 'Grand Master');
 foreach ($leagues as $key=>$value) {
      $selected = ($value == $user_data['league'] ? ' checked="checked"' :  '');
      echo '<label><input type="radio" name="league"' . $selected . ' value="' . $value . '">' . $value . '</label> ';
 }
?>

<script>
var value = <? /* Your PHP code to get the stored value from the db...*/ ?>;

/* radioOptions will store the array of radio buttons.*/
var radioOptions = document.getElementsByName("league");
var i;
for (i = 0; i < radioOptions.length; i++) {
    /* Check if the value of the radio option matches the stored value.*/
    if (radioOptions[i] === value) {
        radioOptions[i].checked = true;
        /* No need to check the others.*/
        break;
    }
}    
</script>

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