Search code examples
javascriptjquerydjangodjango-taggit

Suggestion-tags appear on click in input Django


Hello im using Django with Taggit(Selectize) and I would like to give users the option to click on "suggestion-tags" and that they appear in the input field. I wrote some JS its working in the console but not in the template. No tags appear in the input field but the given tags are saved and when the user reloads the page the tags are displayed in the Input field.

$('.tags_select a').click(function() {
  var valueText = $(this).text();
  var input = $('#id_I_want');
  oldInput = input.val();
  $('#id_I_want').val(oldInput + " " + valueText);
  newInput = input.val();
  $(input).text(newInput);
  return false;
});
{% load widget_tweaks %}
<p class="formItems"> {{ SetForm.I_want|add_class:"" }}</p>
<div class="tags_select">
  <span>Tags</span>
  <a href="#">Fun</a>
  <a href="#">Lala</a>
  <a href="#">Airline</a>
</div>

I also tried to do an ajax call but same thing saved and displayed in the console but not shown in template when clicked. It is a Django form. I think that is the problem or it has something to to with Taggit.

Does anybody know how I can make the tags appear immediately when they are clicked? enter image description here

EDIT: so to make clear what i am trying to do: If a User clicks on one of these "Trending Tags" it should appear in the input field where the other (already selected) Tags are.

SOLUTION: So thanks to @Håken Lid I found this Solution for Selectize with Taggit:

 $('.tags_select a').click(function() {
  var selectize = $("#id_I_want_to_see")[0].selectize;
  value = $(this).text();
  selectize.createItem(value)
});

Solution

  • The problem is caused by Selectize. To get the fancy input, it hides the actual input element, and shows a div instead. Div can have child elements with styling, unlike input. The problem is that there's no two way binding. So even if you update the hidden input, the selectize-input does not reflect those changes.

    You should be able to find a solution to how you can update the value in a selectize-input by refering to the selectize api docs: https://github.com/selectize/selectize.js/blob/master/docs/api.md

    $('.tags_select a').click(function() {
      var selectize = $("#id_I_want_to_see")[0].selectize;
      value = $(this).text();
      selectize.createItem(value)
    });