简体   繁体   English

如何根据数据库值在组中设置默认的选定单选按钮?

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

html: 的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?). 我有一个数据库列,该列会将他们选择的列另存为VARCHAR(我应该使用其他名称吗?)。 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。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM