如何在Django脆皮表单中使用JS启用/禁用复选框按钮

How to enable/disable button with checkbox using JS inside Django crispy form?

本文关键字:启用 JS 按钮 复选框 Django 表单      更新时间:2023-09-26

我想实现这个:http://jsfiddle.net/8YBu5/7/

我想启用/禁用django脆表单提交按钮基于一个复选框在相同的脆表单。

有可能吗?我如何让这个JS工作?

JS似乎没有做任何事情。我觉得我在这里错过了一些基本的东西…

这是我的脆的形式:

email = forms.EmailField(label=_("Email"))
password1 = forms.CharField(widget=forms.PasswordInput,label=_("Password"))
billing_secret = forms.CharField()
termsandcond = forms.TypedChoiceField(
        label = False,
        choices = ((1, "Yeah sure"),),
        initial = '0',
    )
def __init__(self, *args, **kwargs):
    billing_secret = kwargs.pop('billing_secret', None)
    super(RegistrationForm, self).__init__(*args, **kwargs)
    self.helper = FormHelper()
    self.helper.form_method = 'post'
    self.helper.form_action = '.'
    self.helper.layout = Layout(
        Field('email', placeholder=_("Email")),
        Field('password1', placeholder=_("Password")),
        InlineCheckboxes('termsandcond'),
        Submit("save", _("Get Started"),css_class="pull-right", css_id="postme"),
    )

这是我的JS:

$('#id_termsandcond_1').click(function(){
    if($(this).attr('checked') == false){
         $('#postme').attr("disabled","disabled");   
    }
    else {
        $('#postme').removeAttr('disabled');
    }
});

下面是相关的django crispy form元素:

<div id="div_id_termsandcond" class="form-group">
    <div class="controls ">
        <label class="checkbox-inline">
            <input type="checkbox" name="termsandcond" id="id_termsandcond_1" value="1">Yeah sure
        </label>
    </div>
</div>
<input type="submit" name="save" value="Get Started" class="btn btn-primary pull-right" id="postme">

可以。你需要使用。prop('checked')。

<html>
<body>
    <form action="/somehandler.html" method="get">
        <div id="div_id_termsandcond" class="form-group" >
            <div class="controls ">
                <label class="checkbox-inline">
                    <input type="checkbox" name="termsandcond" id="id_termsandcond_1" value="1">Yeah sure
                </label>
            </div>
        </div>
        <input type="submit" name="save" value="Get Started" class="btn btn-primary pull-right" id="postme">
    </form>
    <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script type="text/javascript">
        $('#postme').attr('disabled', 'disabled');
        $('#id_termsandcond_1').click(function(){
            if($(this).prop('checked')  === false){
                $('#postme').attr('disabled', 'disabled');
            }else {
                $('#postme').removeAttr('disabled');
            }
        });
    </script>
</body>
</html>