I have a django template variable {% clients_list %}
I want to load this in multiple select boxes with same prefixes.
I am writing this code:
$(document).ready(function(){
for (i=1; i<=30; i++){
for(j=0; j<=clients_list.length - 1; j++){
$('#client'+i).append($('<option>')
.text(clients_list[j])
.attr('value', clients_list[j]));
}
}
});
But I am facing this error:
ReferenceError: clients_list is not defined
Help me please!
As always, encode as JSON.
{% load jsonify %}
var clients_list = {{ clients_list|jsonify }};
Related
This question already has answers here:
JavaScript raises SyntaxError with data rendered in Jinja template
(3 answers)
Closed 4 years ago.
I am using Flask to get python lists into HTML. To iterate through the lists and print every elements, I use Javascript.
<script type="text/javascript">
function show_tests(test, desc) {
text = "";
for (i = 0; i < len(desc); i++) {
text += "<tr><td>" + test[i] + "</td><td>" + desc[i] + "</td></tr>";
}
return text;
}
</script>
And the call is
<tbody>
<script type="text/javascript">document.write(show_tests({{ tests }}, {{ descriptions }}));</script>
</tbody>
When I run Flask and open the HTML, the data from JS dosen't show up. Anyone has any idea on why that is?
**BTW: desc and test ALWAYS have same length.
Any help is appreciated!!
EDIT: anyone else having this problem: use jinja! I just learned about it and it's great!!
There's no reason to be using JS here at all. There is nothing interactive here, you should do it directly in Jinja2.
view:
...
return render_template('mytemplate.html', zipped_tests=zip(tests, descriptions))
template:
<tbody>
{% for test, desc in zipped_tests %}
<tr><td>{{ test }}</td><td>{{ desc }}</td></tr>
{% endfor %}
</tbody>
I am trying to generate random numbers between 1 to 132 (inclusive) using JavaScript, when a user clicks on a button.
So far so good, it generates the value and I am able to get the desired output.
The problem:
I was to use the generated value in a custom Django filter (or whatever it is called). Let me explain it better with my code:
<script type="text/javascript">
function random_generator()
{
var rand = [];
var i;
var j;
var text = "";
for(i = 0; i < 5; ++i)
{
rand[i] = Math.floor((Math.random() * 132) + 1);
text += rand[i];
}
document.getElementById('rand1').innerHTML = text; //Just trying to see if the numbers are generated properly
var text2 = "{%for i in allb %}{%if i.id == " + text + "|add:0 %}<p>{{ i.name }}</p>{% endif %}{%endfor%}";
document.getElementById('rand2').innerHTML = text2;
document.writeln(rand[0]);
}
</script>
Here's what else I tried doing:
<div id="b005" class="modal">
<div id="rand1"></div>
<div id="rand2"></div>
{%for i in allb %}
{%if i.id == **WANT TO USE THE JS VARIABLE HERE**|add:0 %}
<p>{{ i.name }}</p>
{% endif %}
{%endfor%}
</div>
Note:allb is an object that I have passed from my views.py
Is there any other way of doing the same?
Thank you in advance :)
As Daniel already mentioned, you have to first understand what is going on behind the scenes. Your django templates only exist on your server, and all template code gets executed on that server. This template code can be used for non-html rendering as well, as you are doing in your random_generator() script.
But the browser receives only an evaluated version of the templates. So it is impossible to compare your django template code (server-side) to your client-side js.
I am working on a django app where I made a custom view that passes a queryset of elements to the rendered html page.
In the html page I want to have an option to select a word from a select list and If the selected word matches any element from the list I got from view, I should need to display it.
I tried using Java script to read these elements into array and then use that array on chnage in select box. but it didnt work as I required.
Here is what I have done so far.
View:
from .models import words as m
def test(request):
words = m.objects.all()
context = Context({
'words': words,
})
return render(request, 'newpage.html',context)
newpage.html:
<select id="sel" onChange="func();">
<option value="" selected="selected">--none--</option>
<option value="word1">word1</option>
....
<option value="wordn">wordn</option>
</select>
<script>
function func()
{
var e = document.getElementById("sel");
var str = e.options[e.selectedIndex].value;
'{% for each in words %}'
var a="{{ each.word }}";
if(str===a)
{
console.log('{{each.word }}')//or passing it to a div in html
}
{% endfor %}
}
</script>
what I require is If the selected element is "word1" and if the queryset "words" has "word1" in it, it should display the word in the page in any div
can any one help me understand the right way to use this queryset object in the html/js.
Fix your script like the following, this should work for you:
<script>
function func() {
var e = document.getElementById("sel");
var str = e.options[e.selectedIndex].value;
"{% for each in words %}"
var a = "{{ each.word }}";
if(str === a) {
console.log("{{ each.word }}")
}
"{% endfor %}"
}
</script>
Try something like this:
<script>
var words = [
{% for word in words %}
"{{ word }}",
{% endfor %}
];
function func() {
var e = document.getElementById("sel");
var str = e.options[e.selectedIndex].value;
for (var word = 0; word < words.length; word++) {
if (words[word] === str) {
console.log(words[word]);
}
}
}
</script>
The code I'm writing is supossed to fetch a set of airports urls, and assign them to an array by code-url.
This is what I have so far:
<script>
var airport = new Array();
function CheckAirportCode(){
{% for x in linklists['airports'].links %}
var y = {{x.url}};
y = y.match(/\/([A-Za-z0-9]{3})\-/);
airport[y] = {{x.url}};
{% endfor %}
}
$(document).ready(CheckAirportCode());
</script>
but when I load the page and access the variable from the console browser, it says it is undefined. Any pointers ?
I have a jsp page wherein I've used javascript function and I'm calling this using onClick present inside a form:
<script type="text/javascript">
function fa(){
<%
String as = null;
int aa =10;
for(int q =0; q<=aa ; q++){
if(q==5){
as="asds";
}
}
%>
<%= as%>
}
</script>
I'm a little confused about using javascript in a jsp page. How do I use the for loop? Usually, for loop can be called directly inside a js but since this is a jsp page, how will I use it? Do I have to call forEach instead? Right now, this code does not work.
You can use the for loop of JavaScript itself.
<script type="text/javascript">
function fa(){
var as = null;
var aa =10;
for(var q =0; q<=(Number)aa ; q++){
if((Number)q==(Number)5){
as="asds";
}
}
alert(as);
}
</script>