簡體   English   中英

根據從MySQL數據庫返回的JSON將單選按鈕設置為選中狀態

[英]Set radio button to checked based on returned JSON from MySQL database

當我從中選擇一個值時,需要自動填充其中一種怪異的表格。 全部使用$ .ajax以及PHP和JSON完成。 到目前為止,除一種特殊類型的控件(單選按鈕)外,大多數HTML控件都可以毫無問題地填充。 我試圖根據MySQL在JSON中返回的內容,將HTML表單中的單選按鈕設置為單選按鈕組中的選中狀態。

在MySQL中,我將單選按鈕狀態值存儲為01整數,表示是或否。

數據庫中單選按鈕狀態的列名稱為subscribe_status 單選按鈕HTML控件的表單名稱為subscribe-status我將對其進行更改,以免稍后混淆 )。

此刻發生的事情是……什么都沒有。 我不知道為什么。

jQuery更改單選按鈕狀態

// property defined?
if(output[0].subscribe_status !== undefined){
    // none of radio buttons are checked?
    if($('input[name=subscribe-status]').is(':checked') === false) {
        // check one based on returned JSON
        if(output[0].subscribe_status === 0){
            $('input[name=subscribe-status]').filter('[value=0]').prop('checked', true);
        }else if(output[0].subscribe_status === 1){
            $('input[name=subscribe-status]').filter('[value=1]').prop('checked', true);
        }
    }
}else{
    console.log("Subscribe status property is undefined");
}

我在$.ajax調用中success執行了這些操作,它適用於其他HTML控件,例如<text><textarea><select>類型的輸入,但不適用於單選按鈕。 MySQL結果作為Object存儲到output變量中。

HTML形式:

<div class="form-group">
    <label for="subscribe-status" class="sr-only">Subscribed?:</label>
    <label for="subscribe-status">Subscribed?:</label>
    <div class="radio-inline">
        <label for="subscribe-status"><input type="radio" name="subscribe-status" value="1" />Yes</label>
    </div>
    <div class="radio-inline">
        <label for="subscribe-status"><input type="radio" name="subscribe-status" value="0">No</label>
    </div>
</div>

注意:我使用Bootstrap。

不需要if...else

$('input[name="subscribe-status"][value="' + output[0].subscribe_status + '"]').prop('checked', true);

這將選擇具有name屬性的input元素,作為subscribe-status並將value作為output[0].subscribe_status值。

確保您的output變量為JSON且包含subscribe_status

你這里有錯誤

$("input[name=subscribe-status]')

您以雙引號開始,以單引號結束。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM