javascript - 如何在单击单选按钮时使按钮处于非事件状态?

标签 javascript jquery html django django-forms

我想让提交按钮处于非事件状态(不可点击),直到选中表单的单选按钮之一。

这是我目前所拥有的:

{% for answer in form.poll.answers.all %}
    <p class='field radio question'>
        <input id='{{ form.answer.auto_id }}_{{ answer.pk }}' type='radio' name='{{ form.answer.html_name }}' value='{{ answer.pk }}' />
        <label for='{{ form.answer.auto_id }}_{{ answer.pk }}'>
            <em>{{ answer }}</em>
        </label>
    </p>
{% endfor %}

<button class='buttons' type='submit' id='id_vote_button'>{% trans "Vote" %}</button>

<script src='{% static 'scripts/libs/jquery.js' %}'></script>

<script>
    $("input.radio").on('click', function () {
        console.log("click test");
        if ($('form.poll input.radio:checked')[0]) {
            console.log("true test");
            $("#id_vote_button").setAttribute('active', true);
        }
        else {
            console.log("false test");
            $("#id_vote_button").setAttribute('active', false);
        }
    });
</script>

问题是当我点击单选按钮时,$("input.radio").on('click', function () 不会对控制台产生任何影响。

最佳答案

您需要设置按钮的disabled 属性,这可以通过使用.prop() 来实现。方法并使用正确的选择器 :radio 来定位单选元素。

$(":radio").on('change', function () {
    $("#id_vote_button").prop('disabled', $('form.poll :radio:checked').length == 0);
});

我建议您使用 change 事件而不是 click

注意:jQuery 中没有定义setAttribute() 方法

关于javascript - 如何在单击单选按钮时使按钮处于非事件状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45190114/

相关文章:

html - 使用 YouTube 上传小部件的预定义帐户

javascript - Array.filter 没有返回所需的输出

javascript - 使用 Javascript 将文本从 Textarea 保存到 Google Drive

javascript - 在 Html 中,为什么单击表单中的常规按钮会执行表单操作

javascript - 通过访问其他域覆盖 iframe/跨域中的 css

javascript - 当按钮被禁用时创建警报

jQuery - 在新窗口中打开 id 中的所有链接

html - 是否可以使用 bootstrap 4 在右侧添加偏移量?

javascript - AngularJs 选择器?

javascript - 输入 "process"关键字时,使用 JavaScript 文件的 VS Code 出现 IntelliSense 问题