【问题标题】:Django template - checkbox did not react when is selectDjango模板-选择时复选框没有反应
【发布时间】:2017-05-15 17:55:04
【问题描述】:

我在 django 中有应用程序并且我更新了我的模型:

is_promoted_post = models.BooleanField(default=False)
promoted_from = models.DateTimeField(blank=True, null=True)
promoted_to = models.DateTimeField(blank=True, null=True)
promoted_budget = models.CharField(max_length=70, blank=True, null=True)

我的目标是选择is_promoted_post 字段时剩余字段的外观。

在模板中我有:

<h2>Promoted post</h2>
  <label>Promoted post?</label>
    {{ form.is_promoted_post }}
    <br><br>

  <label>Promoted date from</label>
    {{ form.promoted_from }}

  <label>Promoted date to</label>
    {{ form.promoted_to }}

  <label>Promoted budget</label>
    {{ form.promoted_budget }}

当我使用 Firebug 获取有关 is_promoted_post 的更多详细信息时,我得到:

<input checked="checked" id="id_is_promoted_post" name="is_promoted_post" type="checkbox">

我尝试启动我的 js 代码,但是当我选择没有保存模型的复选框时,代码没有响应。

我的js代码:

  $(document).ready(function(){
      if ($('input#id_is_promoted_post').prop('checked')) {
        alert('Test test');
        }
    });

感谢您的帮助。

【问题讨论】:

    标签: javascript jquery python django checkbox


    【解决方案1】:

    试试:

    $(document).ready(function(){
      if ($('#id_is_promoted_post').prop('checked')) {
        alert('Test test');
        }
    });
    

    【讨论】:

      【解决方案2】:

      如果你想触发check/uncheck,试试这个

      $('#id_is_promoted_post').change(function() {
          if(this.checked) {
              alert("checked")
              return false;
          }
          alert("unchecked")       
      });
      

      【讨论】:

        【解决方案3】:

        $('#id_is_promoted_post').is(':checked') 将返回 true 如果 checkbox 被检查或 false 不同。 所以你也可以试试下面的代码:

         $(document).ready(function(){
          if ($('#id_is_promoted_post').is(':checked')) {
            alert('Test test');
            }
        });
        

        【讨论】:

          猜你喜欢
          • 2021-08-27
          • 1970-01-01
          • 2016-12-04
          • 1970-01-01
          • 2017-11-20
          • 2011-06-21
          • 2015-12-11
          • 1970-01-01
          • 2015-12-14
          相关资源
          最近更新 更多