0

could anybody suggest how I can put the javascript variable into the html href tag and code. Specifically, when loading the page, I want the following code can define div id and pass as the argument in its javascript function toggle 5 with the values of count_newsCat. For example, the first div would have id 'newsCat1', the second one 'newsCat2', etc..

The code is as below:

   <script>count_newsCat = 1;</script>
    {% for tag_field in tag_table %}
    <div name="{{tag_field.tag_name}}" class="tile" id="newsCat_gp" >
      <span onclick="this.parentNode.style.display = 'none';" class="closebtn">&times;</span>
      <a id="imageDivLink" href="javascript:toggle5('newsCat' + count_newsCat, 'list_div', 'imageDivLink');"><img src=  "{% static '/img/minus.png' %}"></a>
      <div class="tile__name"><b><font size="2px">{{tag_field.tag_name}}</b></font></div>
      <div class="tile__list" id="newsCat" + <script>count_newsCat;</script> style="display: block;"></div>                   
    </div>  
    <script>count_newsCat++;</script>
    {% endfor %} 

Many thanks!

1
  • Not surprisingly, native dom and browser doesn't support this. You can only achieve this with some templating system(underscore templates for example) that compiles to static html files. Commented Jan 15, 2017 at 8:56

1 Answer 1

1

if you use ES5 you could use templates like this:

`<a href='javascript:toggle5("${DivID}","list_div","imageLink")'>Link</a>`

if not, you could do the same with any template library like handlebar, so It will be like this:

for(var x = 10; x > 0; x--){
  var html = handlebar(source, {id:x,div:"list_div",link:"imageLink"})
  return template(html)
}// I dont remember pretty well the syntax of handlebars, find it in google

and your template will be something like this

<a href='javascript:toggle5("{{DivID}}","{{list_div}}","{{imageLink}}")'>Link</a>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot for the solution, I just figure out that I can achieve the same purpose in the Django template by using {{ forloop.counter }} which will do what count_newsCat++ does.
Glad to help, happy coding!

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.