【问题标题】:How do I make a button inactive on radio button click?如何在单选按钮单击时使按钮无效?
【发布时间】:2017-12-24 16:46:29
【问题描述】:

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

这是我目前所拥有的:

{% 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 () 在控制台中没有任何影响。

【问题讨论】:

  • $(".radio input").on('click', function(){console.log(1)})...试试这个...让我们知道

标签: javascript jquery html django django-forms


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

    我认为你不应该捕捉 'click' 事件,而应该捕捉 'change' 事件。

    $("input.radio").on('change', function () {
    ...
    }
    

    $("input.radio").change(function () {
        ...
    }
    

    【讨论】:

      【解决方案3】:

      我使用了 Satpals 的答案,但使用 jQuery 提供的 .is() 函数将其更改为跟随

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

      或者你甚至可以使用$(this)

      $('input.radio').on('change', function () {
          $('#id_vote_button').prop('disabled', $(this).is(':checked'));
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-17
        • 1970-01-01
        • 1970-01-01
        • 2021-08-12
        相关资源
        最近更新 更多