Django jQuery not working? - javascript

This is what my template looks like:
{% extends 'typer/base.html' %}
{% load url from future %}
{% load staticfiles %}
{% block title %}{{ p_name }}{% endblock %}
{% block body_block %}
<script type='text/javascript'
src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script>
$('#user_passage_text').on('keyup', function(e) {
if ( e.which === 13 ) {
var time = (new Date()).getTime() - $(this).data('time');
$(this).data('time', 0);
console.log('Time passed : ' + time + ' milliseconds');
}else if ( !$(this).data('time') ){
$(this).data('time', (new Date()).getTime());
}
});
</script>
<h1>{{ p_name }}</h1>
<p>This passage is {{ p_wlength }} words, {{ p_clength }} characters long.</p>
{% if passage %}
<p><blockquote>{{ p_text_body|linebreaksbr }}</blockquote></p>
{% else %}
The specified text {{ p_name }} does not exist!
{% endif %}
<p>
Begin typing to start the test.
</p>
<textarea id="user_passage_text"></textarea>
{% endblock %}
All I want for this to do is print a message to the console to check that the function is working. The reason I'm confused about it not working is that I can run it on http://jsfiddle.net/d8c4z300/ perfectly fine. So why does the message print there but not when I run the django template?

you need $(function(){ ... }) (or $( document ).ready(function() { ... }); which is equal, only longer) around your js code:
so:
$(function(){
$('#user_passage_text').on('keyup', function(e) {
if ( e.which === 13 ) {
var time = (new Date()).getTime() - $(this).data('time');
$(this).data('time', 0);
console.log('Time passed : ' + time + ' milliseconds');
}else if ( !$(this).data('time') ){
$(this).data('time', (new Date()).getTime());
}
});
});
fiddle is working because you set it to onload which is almost equal to $(function(){ ... }) here.

Related

How do I load a Shopify blog view/template on a tag even if there are no articles for that tag?

Expected Result:
As the title says, I'm trying to get the custom hero section of my template to load, even when they are no articles for a tag.
Actual Result:
The behavior right now is intermittent. Some tags will load the hero but most won't.
Errors:
In the console on the ones that don't work I receive a 'GET 404' error and my 404 page loads. On the ones that are working I'm not getting any error.
The HTML:
<div id="blog-hero">
<!-- blog hero goes here -->
</div>
<div id="article-index-background">
<div id="article-section" class="width g-flex">
<!-- paginate articles here -->
</div>
</div>
The JS:
// get the hero
const pathName = window.location.pathname;
let blog_div = document.getElementById('blog-hero');
let blogName = pathName.split('/')[2];
let tagName = pathName.split('/')[4];
let request = new XMLHttpRequest();
request.open('GET', `/?section_id=blog--hero-${blogName}-blog--${tagName}`)
request.onload = () => {
if(request.readyState === request.DONE) {
if (request.status === 200) {
blog_div.innerHTML = request.responseText;
}
}
};
request.send(null);
// load the articles, paginate on screen width
let screenWidth = window.innerWidth;
let articleSection = document.getElementById('article-section');
if (screenWidth < 600) {
articleSection.innerHTML = `
{% if blog.articles %}
{% paginate blog.articles by 3 %}
{% for article in blog.articles %}
// some html
{% endfor %}
{% endpaginate %}
{% endif %}
`
} else if (screenWidth >= 600) {
articleSection.innerHTML = `
{% if blog.articles %}
{% paginate blog.articles by 6 %}
{% for article in blog.articles %}
// some html
{% endfor %}
{% endpaginate %}
{% endif %}
`
}
A simply workaround I implemented to solve this was to make a post on the blog with the title "Hidden Post" and hide any blog article with that title on the frontend. Kinda hacky, but it works.

How to compare Django template language variables with javascript variables?

I've got something like this in my Django template:
<script>
var selected_direction = $("#id_direction").val();
{% for bus_stop in bus_stops %}
{% if bus_stop.direction == selected_direction %}
// Do something //
{% endif %}
{% endfor %}
</script>
I can do everything with bus_stops until it reaches the {% if %} statement. How can i compare javascript variable with django variable?
/Edit
Maybe the question was not constructed properly. However i solved my problem by doing this:
<script>
var selected_direction = $("#id_direction").val();
var temp_direction;
{% for bus_stop in bus_stops %}
temp_direction = "{{ stop.direction }}";
if (temp_direction == selected_direction){
////////
///////
}
{% endfor %}
</script>
you can compare this condition
{% if bus_stop.direction == selected_direction %}
by converting you template value to js value, and compare it in js if condition as follows.
if(selected_direction == '{{bus_stop.direction}}')
{
//code here
}
Here is a post that explains how they work together. There is a injection risk involved with this. Maybe make an ajax call for your data and do everything in javscript.

How would I write an if/else statement for something that is undefined with a twig var?

I'm using twig to declare a var user:
<script type="text/javascript">
{% if user is defined %}
var user = {
example: {{ userjson | raw }}
};
{% endif %}
</script>
This checks to see if a user is logged in, if not my console returns this:
Uncaught ReferenceError: user is not defined
I want to be able to display a message if the user is not defined but I can't think of a way to do that. Right now I have this:
if(user){
console.log('hello');
} else {
console.log('undefined');
}
// This checks is the user information
var userId = user.example.id;
console.log(user.example.money);
Ok so I figured this out:
<script type="text/javascript">
{% if user is defined %}
var user = {
example: {{ userjson | raw }}
};
{% else %}
var user = false;
{% endif %}
</script>
Then I just check to see if the var user is false, and if it's not then I do something else.

symfony twig javascript function undefined

I'm trying to use an external JS file in my twig. The goal is just to verify client's input.
When I put directly my script in my Transfert.html.twig , my script is well executed but when I used an external file with assetic nothing happen. The link created by assetic is good(I can see my script when i click on it in my web page source code).but firebug says
"SyntaxError: expected expression, got '<'
<script type="text/javascript">" "ReferenceError: verifyMontant is not defined"
I registred my bundle into app/config/config.yml:
" bundles: [FASTTransfertBundle]", so I guess no problem form here
Now this is my code: Transfert.html.twig:
{# src/FAST/TransfertBundle/Resources/views/Default/Transfert.html.twig #}
{% extends "FASTTransfertBundle::layout.html.twig" %}
{% block title %}{{ parent() }} - Index{% endblock %}
{% block body %}
{{ form_label(form.montant) }} {{ form_widget(form.montant,{'attr':{'onblur':'verifyMontant(this)'}}) }}
{% javascripts '#FASTTransfertBundle/Resources/public/javascript/verifyTransfert.js' %}
<script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}
{% endblock %}
And this is my javascript file :
<script type="text/javascript">
//color if wrong
function changeColor(field,error)
{
if(error)
field.style.backgroundColor = "#fba";
else
field.style.backgroundColor = "";
}
function verifyMontant(field)
{
var montant= field.value.replace(/\D+/g,'');
var regex = /^\-?[0-9]*\.?[0-9]+$/;
if(!regex.test(field.value)){
changeColor(field, true);
return false;
}
else if(montant.length != 11){
changeColor(field, true);
return false;
}
else{
changeColor(field,false);
return true;
}
}
</script>
You must remove
<script type="text/javascript">
from your javascript file.

Using Django Templates, how can I access values from my model in the JavaScript header?

Using Django, I can successfully read and display values from my model in the content segment of my template, but I can't get the values from my model in the head segment of my template.
Here's the code -->
view.py:
from django.shortcuts import render_to_response
from django.template import RequestContext
from host.models import Event
def EventSingle(request, slug):
return render_to_response('event.html', {'eventobject': Event.objects.get(slug=slug)})
event.html:
{% extends "base.html" %}
{% block extrahead %}
<script type="text/javascript" src="https://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
var variable1;
variable1="click worked";
//variable1={{ eventobject.datetime }};
$(document).ready(function () {
$("#pic").click(function (b) {
alert(variable1);
});
});
</script>
{% endblock %}
{% block content %}
<div id="eventobject">
<p>{{ eventobject }}</p>
<p>{{ eventobject.location }}</p>
<p>{{ eventobject.datetime }}</p>
<img id="pic" src="{{ eventobject.image1.url }}" />
</div>
{% endblock %}
When clicking on the image, an alert box pops up with the text "click worked", but if I comment out variable1="click worked"; and un-comment variable1={{ eventobject.datetime }}; nothing happens when I click on the image. Can I not use model references in the head section of django template? All other references to the model in the content block display the values from the DB properly.
I guess eventobject.datetime must be a string or python datetime object.
If it is a string, change your code to :
variable1= "{{ eventobject.datetime }}" ;
If it is a datetime object, use django template filter :
variable1= "{{ eventobject.datetime|date:"D d M Y" }}"
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
If you do not put the quotes, the javascript statement looks like:
variable1 = 2013-05-30 ;
which is INCORRECT javascript syntax, the quotes are needed.
Per Django docs, you can use a date filter to format date:
variable1= '{{ eventobject.datetime|date:"d-m-Y" }}';
Additionally, you can also set DATE_FORMAT (or DATETIME_FORMAT) setting to set a project-wide default for displaying such values.

Categories

Resources