Kai
Kai

Reputation: 593

Django template - checkbox did not react when is select

I have app in django and I updated my model:

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)

My goals are the appearance of the remaining fields when the is_promoted_post field is selected.

In template I have:

<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 }}

When I use Firebug to get more details about is_promoted_post I get:

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

I tried do start my js code but code did not respond when I selected checkbox without save model.

My js code:

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

Thanks for any help.

Upvotes: 0

Views: 456

Answers (3)

Sathish Kumar VG
Sathish Kumar VG

Reputation: 2172

$('#id_is_promoted_post').is(':checked') will return true if the checkbox gets checked or false differently. So you can also try with the following code:

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

Upvotes: 0

itzMEonTV
itzMEonTV

Reputation: 20339

Try this if you want trigger check/uncheck

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

Upvotes: 0

HenryM
HenryM

Reputation: 5793

Try:

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

Upvotes: 1

Related Questions