Django - Javascript not working in templates - javascript

I am trying to display an input field based on user choice selection. Learning from stackoverflow, I have written the following code:
<form action="/register/" method="post" enctype="multipart/form-data">{% csrf_token %}
<select name="designation" id="designation">
<option value="faculty">Faculty</option>
<option value="student">Student</option>
</select>
<div id="students" style="display:none;">
<input type="file" name="uploadFile">
</div>
</form>
<script type="text/javascript">
$('#designation').on('change',function(){
if( $(this).val()==="student"){
$("#students").show()
}
else{
$("#students").hide()
}
});
</script>
The code does work in https://jsfiddle.net/. However, when I am trying to use it in my django template its not working.(i.e., on selecting 'student' nothing appears). I have the following included as well in my base.html.
<script src="{% static 'jquery-3.2.1.min.js' %}"></script>
<script src="{% static 'js/bootstrap.min.js' %}" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
UPDATE:
base.html: hideshow.js is the script.
<!DOCTYPE html>
{% load staticfiles %}
{% load static %}
<html lang="en"
xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<link href="{% static 'css/bootstrap-dist.min.css' %}" rel="stylesheet">
<link href="{% static 'css/ie10-viewport-bug-workaround.css' %}" rel="stylesheet">
<script src="{% static 'JS/html5shiv.min.js' %}"></script>
<script src="{% static 'JS/respond.min.js' %}"></script>
<script src="{% static 'JS/hideshow.js' %}"></script>
<link href="{% static 'css/carousel.css' %}" rel="stylesheet">
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="{% static 'css/bootstrap-theme.min.css' %}" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="{% static 'css/sampleLogin.css' %}" />
</head>
<body>
{% include "messages_display.html" %}
<br />
{% include "navbar.html" %}
{% block content %}
{% endblock %}
register.html:
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container">
<div class="col-md-12">
<div class="col-sm-7 col-sm-offset-2">
<h1>{{ title }}</h1><br />
<form action="/register/" method="post" enctype="multipart/form-data">{% csrf_token %}
<select name="designation" id="designation">
<option value="faculty">Faculty</option>
<option value="student">Student</option>
</select>
<div id="students" style="display:none;">
<input type="file" name="uploadFile">
</div>
</form>
{% endblock content %}
Please help.

First you have to include jquery.min.js file in html file. Then you have to keep js code in $(document).ready(function().then your code will work
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#designation').on('change',function(){
console.log($(this).val());
if( $(this).val()==="student"){
$("#students").show()
}
else{
$("#students").hide()
}
});
});
</script>
<select name="designation" id="designation">
<option value="faculty">Faculty</option>
<option value="student">Student</option>
</select>
<div id="students" style="display:none;">
<input type="file" name="uploadFile">
</div>

Related

JS: the use of edatagrid

I have problem in using edatagrid.
The red area is a select, the yellow area is *table *by edatagrid. I want to refresh the content of the table when I change the selected value of the select.
I attempted to separate the table from the whole page. When I change the selected value, send a ajax post request to get new data. But the result was the table's style was not like before, and the content of the table was not get refreshed. Like this,
Here is my code.
The whole page: test_plan.html
{% extends 'base.html' %}
{% load static %}
{% block title %} NRLabLims - 测试管理 {% endblock %}
{#控制表格的cs操作#}
{% block css %}
<link href="{% static 'vendor/datatables/dataTables.bootstrap4.min.css' %}" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/themes/icon.css">
<link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/themes/color.css">
<link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/demo/demo.css">
<link href="{% static 'css/sb-admin-2.min.css'%}" rel="stylesheet">
{% endblock %}
{% block js %}
<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="https://www.jeasyui.com/easyui/jquery.easyui.min.js"></script>
<script type="text/javascript" src="https://www.jeasyui.com/easyui/jquery.edatagrid.js"></script>
<script src="{% static 'vendor/datatables/jquery.dataTables.min.js' %} "></script>
<script src="{% static 'vendor/datatables/dataTables.bootstrap4.min.js' %}"></script>
<script src="{% static 'js/demo/datatables-demo.js' %}"></script>
{% endblock %}
<div>
{% block content %}
<div class="container-fluid">
<!-- 页头 -->
<h1 class="h3 mb-2 text-gray-800">测试管理</h1>
<a class="mb-4">测试管理包含test plan、原始记录单、时间记录、错误记录、设备说明书、sop查询、
<!-- 测试管理 -->
{% block test_head %}
<div class="card shadow mb-4">
<div class="card-header py-3">
<div class="align-content-center" >
<h3 class="m-0 font-weight-bold text-primary" >
test plan
</h3>
<select name='testplan' class='' id="testplan" onchange="changePlan()">
{% for testplan in testplans %}
<option value="{{testplan.id}}">{{testplan.testplan_no}}</option>
{% endfor%}
</select>
<button>新增test plan表</button>
</div>
</div>
{%endblock%}
{% block testplanbody %}
<div class="card-body" id="placeHolderContent">
<table id="dg" title="测试用例"
toolbar="#toolbar" pagination="true" idField="id"
rownumbers="true" fitColumns="true" singleSelect="true" resizeHandle="both" style="padding: 0 4px !important;">
<thead>
<tr>
{% for item in items %}
<th field="{{item.nickname}}" width="auto" editor="{type:'validatebox'}">{{item.name}}</th>
{% endfor %}<br>
</tr>
</thead>
</table>
<div id="toolbar">
新增一行记录
删除
保存
撤销
</div>
</div>
{% endblock %}
</div>
</div>
<!-- /.container-fluid -->
{% endblock %}
</div>
{#控制表格的js操作#}
{% block js2 %}
<script>
$(function(){
$('#dg').edatagrid({
url: 'getExcelData',
saveUrl: '/lab/test/saveTestCase',
updateUrl: 'updateTestCase',
destroyUrl: 'deleteTestCase',
});
});
//切换
function changePlan(){
testplanId=$("#testplan").find("option:selected").val();
formData={'testplanId':testplanId};
$.ajax({
type:"GET",
url:"/lab/test/plan",
dataType: "html",
data:formData,
success:function(result){
console.log('result-------');
console.log(result);
$("#placeHolderContent").html(result);
},
error: function (data) {
console.log("data2"+data);
alert("changePlan failed!");
}
});
}
</script>
{% endblock %}
The table part: test_plan_content.html
<div class="card-body" id="placeHolderContent">
<table i`d="dg" title="测试用例"
toolbar="#toolbar" pagination="true" idField="id"
rownumbers="true" fitColumns="true" singleSelect="true" resizeHandle="both" style="padding: 0 4px !important;">
<thead>
<tr>
{% for item in items %}
<th field="{{item.nickname}}" width="auto" editor="{type:'validatebox'}">{{item.name}}</th>
{% endfor %}<br>
</tr>
</thead>
</table>
<div id="toolbar">
新增一行记录
删除
保存
撤销
</div>
</div>
server code:
def test_plan(request):
testplanId=request.GET.get('testplanId')
testplans=Testplan.objects.all()
if(testplanId):
# return the selected one
testplan = Testplan.objects.get(id=testplanId)
testplanId = testplan.id
items = TestplanTableItems.objects.filter(Q(type=testplan.plan_type) | Q(type=0))
return render(request, 'lab_management/test_management/test_plan_content.html',
{ 'items': items})
else:
# return last one
testplan=testplans.last()
testplanId=testplan.id
items = TestplanTableItems.objects.filter(Q(type=testplan.plan_type) | Q(type=0))
return render(request, 'lab_management/test_management/test_plan.html',
{"testplans": testplans, 'items': items})
How to solve it?

Popup rendering with close button but it does not work when clicked?

I have a custom popup that shows upon form submission to let the user know it was successful. Currently it displays when it's supposed to (although I can't get it to display in the middle right on top, but that's a minor issue) like shown below:
But the little X button does not actually close the message. You can click it but it does nothing, and if you reload the page then it's gone until you submit again.
base.html
{% load static purchasing_tags humanize %}
{% include 'operations/message.html' %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="{% static 'images/favicon.ico' %}" type="image/x-icon" rel="shortcut icon"/>
<link href="https://fonts.googleapis.com/css?family=Lato:300,400,700" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href="{% static "css/plugins/bootstrap.min.css" %}" rel="stylesheet">
<link href="{% static "css/apps.css" %}" rel="stylesheet">
<script src="{% static "js/plugins/jquery.js" %}"></script>
<script src="{% static "js/plugins/bootstrap.min.js" %}"></script>
<!--[if lt IE 9]>
<script src="{% static 'js/plugins/respond.js' %}"></script>
<![endif]-->
</head>
<body>
<div id="login" class="panel panel-default">
<div class="panel-body">
{% block main %}
{% endblock main %}
</div>
<div class="panel-footer">
{% block panel_footer %}
{% endblock %}
</div>
</div>
{% if messages %}
<script>
{% for message in messages %}
$(document).ready(function () {
$('.toast').toast('show');
});
{% endfor %}
</script>
{% endif %}
</body>
I think the problem could be related to the warning I get that says Unresolved function or method toast() on $('.toast').toast('show'); but I'm not sure how to resolve this issue (I got this from https://www.w3schools.com/bootstrap4/bootstrap_toast.asp but I don't know if I just didn't add something important to make this work)
enter_exit_area.html
{% extends "base.html" %}
{% load core_tags %}
{% block main %}
<form id="warehouseForm" action="" method="POST" class="form-horizontal" novalidate >
{% csrf_token %}
<div>
<div>
<label>Employee</label>
{{ form.employee_number }}
</div>
<div>
<label>Work Area</label>
{{ form.work_area }}
</div>
<div>
<label>Station</label>
{{ form.station_number }}
</div>
</div>
<div>
<div>
<button type="submit" name="enter_area" value="Enter" >Enter Area</button>
</div>
</div>
</form>
{% endblock main %}
message.html
{% for message in messages %}
<div style="position: absolute" class="toast bg-{% if message.tags == 'error' %}danger{% else %}{{message.tags}}{% endif %}" role="alert" aria-live="assertive" aria-atomic="true" data-delay="5000">
<div>
<strong class="mr-auto">
{{message.tags|capfirst}}
</strong>
<button type="button" class="ml-2 mb-1 close" aria-label="Close">
<span aria-hidden="true" data-dismiss="toast">×</span>
</button>
</div>
<div>
{{message|safe}}
</div>
</div>
{% endfor %}
views.py
class EnterExitArea(CreateView):
model = EmployeeWorkAreaLog
template_name = "operations/enter_exit_area.html"
form_class = WarehouseForm
def form_valid(self, form):
emp_num = form.cleaned_data['employee_number']
area = form.cleaned_data['work_area']
station = form.cleaned_data['station_number']
if 'enter_area' in self.request.POST:
form.save()
EmployeeWorkAreaLog.objects.filter(Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True)).update(time_in=datetime.now())
messages.success(self.request, "You have entered")
return HttpResponseRedirect(self.request.path_info)

How to set up FilePond js image preview

I am trying to use FilePond to allow users to upload drag and drop images. I've set up the FilePond drag and drop and I'm trying to implement the image preview feature. I've attached the css and js and included it in my html. The image preview still isn't working.
{% extends 'main/dashboardbase.html'%}
{% block content %}
{% load static %}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-tofit=no">
<link rel="stylesheet "type="text/css" href="{% static 'main/add.css'%}">
<link rel="stylesheet "type="text/css" href="{% static 'main/filepond.css'%}">
<link rel="stylesheet" type="text/css" href="{% static 'main/filepond-plugin-image-preview.css'%}">
</head>
<body>
<button type="submit" id="add">Save</button>
<a href="{% url 'main:products'%}">
<button id="cancel" >Cancel</button>
</a>
<div class="col-sm-12 col-lg-6" id="inner">
<form method="POST" enctype="multipart/form-data" id="inputform" name="form1">
{% csrf_token %}
<h4>Title</h4>
<input type="text" name="product_title" id="product_title" placeholder="Give your product a name">
<h4>Price</h4>
<input type="text" name="product_price" id="product_price" placeholder="0.00">
<h4>Description</h4>
<input type="text" name="product_description" id="product_description" placeholder="Write a description about your product">
<input type="file" name="product_images">
</form>
</div>
<script type="text/javascript" src="{% static 'main/add.js'%}"></script>
<script src="{% static 'main/filepond-plugin-image-preview.js'%}"></script>
<script src="{% static 'main/filepond.js'%}"></script>
<script>
const inputElement = document.querySelector('input[type="file"]');
const pond = FilePond.create(inputElement);
FilePond.setOptions({
server: '#'
});
</script>
</body>
</html>
{% endblock%}
Make certain that 'filepond-plugin-image-preview.min.css' is loaded. That was my issue.

$().datepicker is not a function

I have added the datepicker function but I am not able to use it. I believe that it is I am doing some fundamental mistake since I am a beginner in javascript and jQuery.
The input tag is in the invite.html file which I am including using django's template tags all the jquery and semantic files I have downloded them in the static folder. I have added the datepicker.js files also I.Thanks in advance. I added and alert in the datepicker script it worked fine, So I think it is the function is added properly but
I get these errors:
jQuery.Deferred exception: $(...).datepicker is not a function
TypeError: $(...).datepicker is not a function
Scholarship.html is the main html file in which I have included the invite.html file and the input tag id="datepicker" is in bold in invite.html the fuction that is generating the is in bold.
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Fusion!
{% block title %}{% endblock %}
</title>
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'globals/semantic-ui/components/reset.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'globals/semantic-ui/components/icon.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'globals/css/semantic.min.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'globals/css/mediaquery.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'globals/css/semantic-notify.css' %}">
<script type="text/javascript" src="{% static 'globals/js/jquery.min.js' %}"> </script>
<script type="text/javascript" src="{% static 'globals/js/jquery.formset.js' %}"> </script>
<script type="text/javascript" src="{% static 'globals/js/semantic-notify.js' %}"> </script>
<script type="text/javascript" src="{% static 'globals/js/ajax-post.js' %}"></script>
{% block css %}
{% endblock %}
</head>
{% comment %}style="background-color: rgba(189, 189, 189, 0.1);"{% endcomment %}
<body id="body">
{% block body %}
{% block navBar %}
{% endblock %}
{% endblock %}
<div id="messages">
{% for message in messages %}
<div class="message" tag="{% if 'success' in message.tags %}green{% elif 'error' in message.tags %}red{% else %} blue {% endif %}" message="{{ message|safe }}"></div>
{% endfor %}
</div>
</body>
<script type="text/javascript" src="{% static 'globals/js/semantic.min.js' %}"></script>
<script type="text/javascript" src="{% static 'globals/js/dropdown.js' %}"></script>
<script type="text/javascript" src="{% static 'globals/js/tab.js' %}"></script>
<script>
$(document).ready(function() {
$('#messages').find('.message').each(function(){
$.uiAlert({
textHead: $(this).attr('message'), // header
text: '',
bgcolor: $(this).attr('tag'), // background-color
textcolor: '#fff', // color
position: 'bottom-left',// position . top And bottom || left / center / right
time: 3, // time
});
});
$('#new-notification')
.popup({
inline: true,
hoverable: true,
position: 'bottom left',
popup: $('#notificationPopup'),
on: 'click',
delay: {
show: 250,
hide: 500
}
})
;
});
</script>
Scholarship.html
{% extends 'globals/base.html' %}
{% load static %}
{% block title %}
Awards & Scholarship
{% endblock %}
{% block body %}
{% block navBar %}
{% include 'dashboard/navbar.html' %}
{% endblock %}
{% block winners %}
{% include 'scholarshipsModule/winners.html' with winners=winners %}
{% endblock %}
</div>
{% comment %}The Personal Details end here!{% endcomment %}
{% comment %}The Publications starts here!{% endcomment %}
<div class="ui tab segment" data-tab="second">
{% block invite %}
{% include 'scholarshipsModule/invite.html' with release=release ch=ch time=time awards=awards form=form %}
{% endblock %} *invite.html is included here*
</div>
</div>
</div>
{% comment %}The right-rail segment ends here!{% endcomment %}
{% comment %}The right-margin segment!{% endcomment %}
<div class="column"></div>
</div>
{% endblock %}
{% block javascript %}
<script src="https://cdn.rawgit.com/mdehoog/Semantic-UI/6e6d051d47b598ebab05857545f242caf2b4b48c/dist/semantic.min.js"></script>
<script type="text/javascript" src="{% static 'globals/js/datepicker.js' %}"></script>
<script type="text/javascript" src="{% static 'globals/js/tablesort.js' %}"></script>
<script type="text/javascript" src="{% static 'globals/js/editProfile.js' %}"></script>
<script type="text/javascript" src="{% static 'globals/js/modal.js' %}"></script>
<script>
$('.message .close')
.on('click', function() {
$(this)
.closest('.message')
.transition('fade')
;
})
;
**$( function() {
$( "#datepicker" ).datepicker(); This is the code that generates the error
} );**
</script>
{% endblock javascript %}
invite.html
{% load static %}
{% block winners %}
<div class="two fields">
<div class="field">
<label>Start date</label>
<div class="ui input large left icon">
<i class="calendar icon"></i>
**<input id="datepicker" type="text" name="From" placeholder="YYYY-MM-DD" required>
</div>**
</div>
<div class="field">
<label>End Date</label>
<div class="ui input large left icon">
<i class="calendar icon"></i>
<input type="text" name="To" placeholder="YYYY-MMM-DD" required>
</div>
</div>
<div class="ui divider"></div>
</div>
</div>
{% endblock %}
This is the datepicker.js fuction which is their in the globals/js folder
datepicker.js script
$('.rangestart').calendar({
type: 'date',
});
$('.rangeend').calendar({
type: 'date',
});
$(".date.calendar").calendar({ type: "date" });
You should add this below script into your site.. after that your error will be remove.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
$('#date1').datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: "m/d/yy"
});
#ui-datepicker-div { font-size: 12px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css"></script>
Date Picker: <input type="text" id="date1" name="date1"/> <br/>

Django template inheritence

In my django app i have a base.html template as follows
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>{% block title %}{% endblock %}</title>
{# ----------------- STATIC FILES -------------- #}
{% load staticfiles %}
<link rel="icon" type="image/x-icon" href="{% static 'images/tab_logo.ico' %}"/>
{% block site_css %}
<link href="{% static 'bootstrap/css/bootstrap.min.css' %}" rel="stylesheet" type="text/css"/>
<link href="{% static 'core/css/style.css' %}" rel="stylesheet" type="text/css"/>
{% endblock %}
{% block extra_css %}{% endblock %}
<meta name="viewport" content="width=device-width">
</head>
<body>
{% block navbar %}
<!-- START NAV -->
<nav role='navigation'>
<a data-page="home" id="home" class="active" href="/">Home</a>
<a data-page="blog" id="blog" href="{% url 'blog' %}">Blog</a>
<a data-page="contact" id="contact" href="{% url 'contact' %}">Contact Us</a>
<a data-page="about" id="about" href="{% url 'about' %}">About</a>
</nav>
<hr>
{% endblock %}
<!--start container-->
<div class="container">
<div class="row">
<div class="span9">
<div id="content">
<br>
{% block content %}{% endblock %}
</div>
</div>
</div>
</div>
<!--end container-->
<hr>
{% include 'core/footer.html' %}
{% block javascript %}
<!-- Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if offline -->
<script src="{% static 'core/js/jquery-3.1.1.min.js' %}"></script>
<script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
<script src="{% static 'core/js/skin.js' %}"></script>
{% endblock %}
{% block add_js %}
{% endblock %}
</body>
</html>
I am trying to make separate template files for blog,about,contact
{% extends 'core/base.html' %}
{% block add_js %}
<script>
$(document).ready(skinchange('blog'));
</script>
{% endblock %}
{% block content %}
<h1 style="text-align: center;font-size: 32px;">BLOG</h1>
{% endblock %}
Now in the index page(nav bar home active), when i click on the blog link (Blog) redirection to localhost:8000/blog/ is done.When this page is loaded i want to change the class of nav a for blog to be active so that the style of the page is changed as per my css.For this i am executing a jquery script -> $(document).ready(skinchange('blog'));
where skinchange is a function in skin.js
'use strict';
function skinchange(page) {
page = typeof page !== 'undefined' ? page : 'home';
var link = $("nav a");
$("body").removeClass().addClass(page);
link.removeClass("active");
var d = document.getElementById(page);
d.className +="active";
}
for some reason on new page loading the class attribute of the nav links remains same as the base.html.The jquery script is not executing.
Can anyone help me what i am doing wrong here.

Categories