0

I have a m_template.html file which has a script as follow:

<script>
     $("#id_country").change(function () {
          var countryId = $(this).val();  // get the selected country ID from the HTML input
          $.ajax({  // initialize an AJAX request
                url: '/ajax/ajax_load_cities',
                data: {
                     'countries': countryId   // add the country id to the GET parameters
                },
                dataType: 'json',
                success: function (data) { // here data comes from url output or load_cities function
                   $("#preview-items").html(data.tags);  
                   }
             });
           });
</script>

In the same template.html I defined a section like:

<div id="preview-items">
     {% for item in itemslist %}
          <label class="btn btn-primary mr-1">
                 <input type="checkbox"  id="checklist" value="{{ item.0 }}">
                  <span>
                     {{ item.1 }}
                  </span>
          </label>
     {% endfor %}
</div>

and load_cieties:

def load_cities(request):
    ....
    
    data = {
        'tags': list(cities)
    }
    return JsonResponse(data)

Where problem happens:

The problem is in the line $("#preview-items").html(data.tags); which rather than passing list, replaces list in the <div> so at the moment I have something like:

id1name1,id2name2,id3name3,...

My Question:

How to pass data.tags which is a list of tuples to section as a parameter that within which I be able to style list items as I already defined in ?

data.tags is something like [(id1, name1), (id2, name2), (id3, name3), ..]

1 Answer 1

1

I would use a bit more sophisticated code (like React), but would this solve the immediate issue?

First, javascript doesn't have tuples, so send it a list of lists (json) from python: [['id1', 'name1'], ['id2', 'name2'], ['id3', 'name3']];

success: function (data) {
    $('#preview-items').html('');
    
    for (var i in data) {
      console.log(i, data);
      $('#preview-items').append(`
        <label class="btn btn-primary mr-1"> 
          <input type="checkbox"  id="checklist" value="` + data[i][0] + `"> 
          <span> 
             ` + data[i][1] + ` 
          </span> 
        </label><br />` 
      );
    }
}

(Note the use of backticks in the javascript multi-line string)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your reply, I tried with both # and #preview-items, but didn't work!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.