0

I need to update an html table cell, which is created using a Django template for loop, once the selection of the pickerselect has changed. My HTML for the table:

        <tbody>
            {% for task in tasks %}
            <tr>
                <td>{{ task.taskNumber }}</td>
                <td>{{ task.taskDescription }}</td>
                <td><div name="dataOutput">{{task.thisPeriod}}</div></td>
            </tr>
            {% endfor %}
        </tbody>

My HTML for the pickerselect:

    <select name="selValue" class="selectpicker">
        <option value="1">Current Period ({{currentPeriod}})</option>
        <option value="2">Previous Period ({{previousPeriod}})</option>
    </select>

My javascript:

<script language="JavaScript">
  $(function() {
      $('.selectpicker').on('change', function(){
        var selected = $(this).find("option:selected").val();
        var updateArray = document.getElementsByName("dataOutput");
        for (var i = 0; 1 < updateArray.length; i++) {
            if (selected == 1) {
                updateArray[i].innerHTML = "{{task.thisPeriod}}";
            } else if (selected == 2) {
                updateArray[i].innerHTML = "temp";
            } 
         }
      });
    });
  </script>

At this point, the table row values update with the placeholder "temp" when selection 2 is made but when I change back to selection 1, no values appear in the table. I assume that this is because the Django template for loop is not being refreshed so it doesn't know how to render for the specific task in the loop {{task.thisPeriod}}. I have looked through a number of questions about refreshing div's using javascript but nothing has been effective... I always get the same result of blank values in the table.

gumbynr
  • 335
  • 3
  • 16

1 Answers1

0

It's kind of obvious, but you can't do it just like that, because javascript doesn't record the tasks django context that you passed to the template. You should use ajax to pass the selected value to a separate method in views.py, in there you find out the data and return it to the javascript, then render the div with the new data.

Shang Wang
  • 24,909
  • 20
  • 73
  • 94
  • Thanks, I figured it was something along those lines. I am new to ajax/javascript so would you mind providing an example? – gumbynr Dec 03 '15 at 20:16
  • There are tons of examples online. I randomly googled and found http://stackoverflow.com/questions/20306981/how-do-i-integrate-ajax-with-django-applications. Apparently you have to read jquery ajax doc as well: http://api.jquery.com/jquery.ajax/ – Shang Wang Dec 03 '15 at 20:19