How to use javascript variables with django or vice versa? - javascript

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.

Related

Javascript won't output to HTML [duplicate]

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>

Can We Append (Chunk of) HTML in jQuery using Html.Partial Helper? C# ASP.Net MVC 5

As the title suggests, I have a chunk of HTML which I put in one of my PartialView:
<div id="meaningPart">
#Html.Partial("_Meaning", new MeaningModel() {number = 1})
</div>
where my _Meaning partial View looks like this:
<div class="chunk">
<!--a lot of html here-->
</div>
Then, I create a jQuery which respond to a <input type="number"/> event (up and down) like the following:
<input id="numberMeaning" type="number" class = "col-md-2 form-control form-control-plus number-input" min = "0" max = "99" value = "1"/>
$(document).ready(function () {
var iCnt = 0;
$("#numberMeaning").on('change', function () {
var num = parseInt($("#numberMeaning").val());
if (num > iCnt) { //up
iCnt++;
$("#meaningPart").append("<p>ok dude, this is really a new item!</p>");
} else { //down
iCnt--;
}
});
});
now, the above code works fine because I simply put "<p>ok dude, this is really a new item!</p>" in the jQuery append, but if I change this part:
$("#meaningPart").append("<p>ok dude, this is really a new item!</p>");
Into
$("#meaningPart").append("#Html.Partial("_Meaning", new MeaningModel() {number = 2})"); //by right, the number should follow iCnt here.
Then, although the razor engine shows that the syntax is correct, the new Partial HTML just doesn't render.
How do we create a new partial HTML using jQuery? Is that possible?
(I am not too familiar with template attribute or jQuery.clone - but if it anyone can show how the adding to the html element can be done using those, I am open to that too)
try it like below
$(document).ready(function () {
var iCnt = 0;
$("#numberMeaning").on('change', function () {
var num = parseInt($("#numberMeaning").val());
if (num > iCnt) { //up
iCnt++;
// your GET /Controller/Action should return "partial HTML" based on iCnt
$("#meaningPart").append($('<div>').load("/Controller/Action?iCnt=" + iCnt));
} else { //down
iCnt--;
}
});
});
your Action in Controller like
public ActionResult Action(int iCnt)
{
//get model based on 'iCnt'
var model = GetModel(iCnt);
return PartialView("~/views/Folder/partialview.cshtml", model);
}
You can use $('#selector').html(content) where content is your template. I cannot imagine to create a partial view using jquery
Short answer: No.
Please be aware of the difference between
JavaScript (Jquery) and
MVC/ASP.Net (Razor).
JavaScript is executed on the client site in the browser.
MVC is executed on the server.
So the server is reading the razor stuff and creating a valid HTML page from it.
This is delivered to the browser.
The browser is creating something the user can see and then is executing the JavaScript.
So what you are doing in your example is trying to get JavaScript to execute a Razor function.
The only way to do something like that would be to use AJAX.
You can do it.
First you need to put the chunk of your partial html to a js var inside your main .cshtml file.
<script>
var chunkHtml = "#Html.Partial("_Meaning", new MeaningModel() {number = 2})"
</script>
and then do your append in your javascript file.
$("#meaningPart").append(chunkHtml);

Increment text in HTML

I am trying to perform this pseudo-code, but can't seem to succeed with my limited knowledge of javascript/jquery..
for i = 0; i < 60; i++
{
<p>This is person *i*</p>}
This will then create 60 HTML lines saying This person is... and its respective number.
I have made a program in VB.NET writing out this code for me, but it makes the HTML document very large.
Is it possible to have these lines displayed without the really written in the file?
In JavaScript you would want to do something like:
for( i = 0; i < 60; i++) {
document.write("<p>This is person "+i+"</p>");
}
Note that you want do call this while the page is loading (place the <script> in where you would want these elements to be), document.write will clear the DOM if it already finished loading. Otherwise you would add this into some container like so:
for( i = 0; i < 60; i++) {
document.getElementById("myContainer").innerHTML += "<p>This is person "+i+"</p>";
}
This should look like this in Html/javascript:
<script>
for(i = 0; i < 60; i++){
document.write("<p>This is person "+i+"</p>");
}
</script>
You can also use jquery:
<script type="text/javascript">
$(function() {
var contents = [];
for (var i=0;i<600;i++) {
contents.push("This is person " + i);
}
$("#content").html(contents.join("<br/>"))
});
<body>
<div id="content">
</div>
</body>
My suggestion would be to use a data binding library like AngularJS. This will greatly reduce the amount of HTML & Javascript you have to write.
JS
var app = angular.module('app', []);
app.controller('Main', ['$scope', function($scope){
$scope.numOfP = [1,2,3];
}]);
HTML
<div ng-app="app">
<div ng-controller="Main">
<p ng-repeat="p in numOfP track by $index">This is person {{ $index }}</p>
</div>
</div>
This will repeat your block of HTML for the give number of array elements in numOfP.
FIDDLE

With Javascript, how to read what is within <span> tags, when the value is created by Javascript

I have this code and I basically want it to read what is created in between the <span> tags (that value is created by another javascript script), and then take that to display 'article' or 'articles'.
<span id="quantity" class="simpleCart_quantity"></span>
<script type="text/javascript">
var q = document.getElementById('quantity');
if (q == 1) {
document.write("article");
}
else
{
document.write("articles");
}
</script>
So I want it to check <span id="quantity" class="simpleCart_quantity"></span>, and if the value that is present is '1', write 'article' and if the value is '0' or more than '1' write 'articles'. I hope you can get it.
Now it works, but only if you actually write something in between the <span>, like:
1
But the value is created externally and the script must be able to read the value that is created when the page is loaded right?
The result should be a sentence that says 'You have x article(s) in your shopping cart'.
I have no idea of how I should do this, I hope somebody can help me.
Thanks a lot!
<span id="quantity" class="simpleCart_quantity"></span>
<!-- ... --->
<span id="quantityText"></span>
<script type="text/javascript">
var quantity = document.getElementById("quantity"),
quantityText = document.getElementById("quantityText");
if (parseInt(quantity.innerHTML, 10) === 1) {
quantityText.innerHTML = "article";
} else {
quantityText.innerHTML = "articles";
}
</script>
Note that you must use a radix argument (10, in this case) to make sure numbers are interpreted as base10. Otherwise everything starting with '0x' would be interpreted as hexadecimal (base16), for example.
alternative syntax using the ternary operator:
<script type="text/javascript">
var quantity = document.getElementById("quantity"),
quantityText = document.getElementById("quantityText"),
quantityValue = parseInt(quantity.innerHTML, 10);
quantityText.innerHTML = "article" + (quantityValue === 1 ? "" : "s");
</script>
In addition to pure javascript, you can also use jQuery:
jQuery($this).find('span.simpleCart_quantity') // find the span with class name: simpleCart_quantity
.text() // get the text

How to work with django template variable and javascript?

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 }};

Categories