(仍然没有答复)django复选框在数据库中保存是或否

2024-02-06

  <form id="form" name="form">
    <input type="checkbox" value="1" name="Asthma" data-form-field="Option" class="form-check-input display-7" id="checkbox1"  title="Check if Student have Asthma">
    <input type="checkbox" value="1" name="Congenital" data-form-field="Option" class="form-check-input display-7" id="checkbox1" title="Check if Student have Congenital Anomalies">
    <input type="checkbox" value="1" name="Contact" data-form-field="Option" class="form-check-input display-7" id="checkbox1" title="Check if Student use Contact lens">
  </form>

我的 html 中有这段代码

<script type="text/javascript">
                        // when page is ready
                        $(document).ready(function() {
                             // on form submit
                            $("#form").on('submit', function() {
                                // to each unchecked checkbox
                                $(this + 'input[type=checkbox]:not(:checked)').each(function () {
                                    // set value 0 and check it
                                    $(this).attr('checked', true).val(0);
                                });
                            })
                        })
                    </script>

我的问题是每次我保存到数据库时结果总是自动是,即使我取消选中html中的复选框(否)。 我不知道我的 javascript 是否做得正确

这是我的观点.py

    Asthma = request.POST['Asthma']
    Congenital = request.POST['Congenital']
    Contact = request.POST['Contact']
V_insert_data = StudentUserMedicalRecord( 
        Asthma=Asthma,
        CongenitalAnomalies=Congenital,
        ContactLenses=Contact
   )
 V_insert_data.save()

模型.py

Asthma=models.BooleanField(null=True, blank=True, default=False)
CongenitalAnomalies=models.BooleanField(null=True,blank=True, default=False)
ContactLenses=models.BooleanField(null=True,blank=True, default=False)

html.py enter image description here

即使我从我的 html 插入记录未被选中(否),结果在我的数据库中总是自动“是”,你能修复我的 javascript 代码吗?似乎它不起作用。


Solution

删除该 Javascript 代码。你不需要它。

更多细节

对于这个问题,你实际上不需要了解 Javascript。评论告诉你发生了什么,但我会尽力澄清:

    // when page is ready
    $(document).ready(function() {
          // on form submit -> This means that this code will run when the form is submitted
        $("#form").on('submit', function() {
            // to each unchecked checkbox -> This means that each checkbox not checked, will run this code below
            $(this + 'input[type=checkbox]:not(:checked)').each(function () {
                // set value 0 and check it -> This means that
                $(this).attr('checked', true).val(0);
            });
        })
    })

如果您想了解更多信息,请使用此代码jQuery https://jquery.com/与功能each https://api.jquery.com/each/(用于循环遍历元素)和attr https://api.jquery.com/attr/函数(用于修改 HTML 元素的属性)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

(仍然没有答复)django复选框在数据库中保存是或否 的相关文章

随机推荐