javascript - 根据从 MySQL 数据库返回的 JSON 将单选按钮设置为选中

标签 javascript php jquery html mysql

当我从 .这一切都是使用 $.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");
}

我在里面执行这些 success$.ajax调用它适用于其他 HTML 控件,例如 <text> 类型的输入, <textarea><select> ,但不是单选按钮。 MySQL 结果存储在 output 中变量为 Object .

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 属性作为 subscribe-status 并且具有 value 作为 input 元素>output[0].subscribe_status 值。

确保您的 output 变量是 JSON 并且它包含 subscribe_status

关于javascript - 根据从 MySQL 数据库返回的 JSON 将单选按钮设置为选中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30917336/

相关文章:

php - 删除文件名中有特殊字符的文件

javascript - 如何在 TinyMCE 中设置响应式文件管理器返回绝对 url

jquery - 尝试从表中获取正确的 'td:nth-child(1)' 值

javascript - 同步任务与异步任务

javascript - 使用 tumblr JSON 呈现自定义照片集

javascript - 在 Druid 查询中使用 Javascript 聚合

javascript - 获取长 CSS 元素并使用 jQuery 更改它们(即::before、:after、:first-child)。

javascript - window.location.href 重定向到空白页

php - 通过 exec() 从 php 调用 php 没有结果

php - 无法安装 Composer Azure 服务器