簡體   English   中英

如何根據數據庫值在組中設置默認的選定單選按鈕?

[英]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>

我有一個數據庫列,該列會將他們選擇的列另存為VARCHAR(我應該使用其他名稱嗎?)。 如何設置它,以便選擇與數據庫中存儲的內容對齊的單選按鈕?

我可能也只是將其更改為下拉菜單,但我仍然需要知道如何為該菜單設置選定的值。

這是我嘗試過的方法,但由於某種原因似乎無法正常工作。

<?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> ';
     }
?>

首先,從數據庫中獲取存儲的值。 您正在使用哪種服務器端語言?

編輯:添加了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