[Answered ]-How to check the checkbox state then show/hide the next input field in Django template

1👍

you can use conditions in Django templates check this article

so your template should be something like this:

 <div class="form-group col-md-6">
            {{ form.non_field_errors }}
            <div class="fieldWrapper">
                {{ form.is_scholorship.errors }}
                <label class="form-label">獎學金</label>
                 {{ form.is_scholorship }} 
            <button type="button" onclick="test()"> 測試 </button>    
            </div>
           
        </div>
       {% if form.is_scholarchip %}
        <div class="form-group col-md-6">
            {{ form.non_field_errors }}
            <div class="fieldWrapper">
                {{ form.scholorship_amount.errors }}
                <label class="form-label">獎學金金額</label>
                {{ form.scholorship_amount }}   
            </div>
           
        </div>
       {% endif %}

0👍

You can use change on your checkbox. So ,whenever user check or uncheck checkbox this event will get call and then depending on if checkbox is checked or not you can disabled or enabled your next input i.e : prop("disabled", false) .

Demo Code :

$(document).ready(function() {
  //onchange of checkbox ..
  $(".outer input[type=checkbox]").on("change", function() {
    //get closest outer div and then -> next outer div->input
    var slector = $(this).closest(".outer").next().find("input")
    //check if the checkbox is checked or not..
    $(this).is(":checked") ? slector.prop("disabled", false) : slector.prop("disabled", true)
    //or to hide/show :
    //$(this).is(":checked") ? slector.closest(".outer").show() : slector.closest(".outer").hide()
  })

  $(".outer input[type=checkbox]").trigger("change")

})
//read more here -> https://api.jquery.com/category/traversing/tree-traversal/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--added outer ...class-->
<div class="form-group col-md-6 outer">
  <div class="fieldWrapper">
    <label class="form-label">獎學金</label>
    <input type="checkbox">
  </div>

</div>
<div class="form-group col-md-6 outer">
  <div class="fieldWrapper">
    <label class="form-label">獎學金金額</label>
    <input type="number">
  </div>

</div>
👤Swati

Leave a comment