Search code examples
jquerydjangoformstimedatetimepicker

How to get jQuery datepicker in loop in django template?


I would like to have the datetimepicker in the input. I can get the clock in the first entry only. how can I get the datetimepicker in all the inputs? Thank you

Here is my html:

<div>
    <table class="table table-hover" border="1" cellpadding="5" cellspacing="5" width="100%" style="width:100%">
      <tr>
        <th>Start</th>
        <th>End</th>
        <th>Update</th>
      </tr>
      {% for b in time_layer %}
      <tr scope="row">
        <form  action="/app/ok_go/"  method="get" autocomplete="off" >
            <td><input type="text" name="Start" id="Start"  value = "{{ b.Start|default:''  }}" size="1"></td>
            <td><input type="text" name="End" id="End"  value = "{{ b.End|default:''  }}"  size="1"></td>
            <input type="hidden" name="id_path" id="id_path"  value = "{{ request.build_absolute_uri  }}"  >
            <td><input class="btn btn-primary btn-sm" type="submit"value="Update"/></td>              
        </form>
      </tr>
      {% endfor %}
    </table>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.js"></script>


<script type="text/javascript">
    jQuery('#Start').datetimepicker({
      datepicker:false,
      format:'H:i'
    });
    jQuery('#End').datetimepicker({
      datepicker:false,
      format:'H:i'
    });
</script>

Solution

  • In HTML, the id parameters must be unique. You are using id="Start", id="End" and id="id_path" inside a loop, meaning that it will be present on the page more then once. Either use classes or append something to each id value inside the loop, like id="Start_{{ forloop.counter }}". docs

    If you are using classes instead of ids, then you can use a single jquery call, like class="datepickeried_input"

    jQuery('.datepickeried_input').datetimepicker({
        datepicker:false,
        format:'H:i'
    });