~[wc:commonscripts]
~[wc:admin_header_css] ~[text:psx.html.admin_reports.runreports.start_page] > PowerSchool Customization ~[wc:admin_navigation_css] ~[SetPostValue:tab=js]JavaScript is a programming language that runs in web browsers and makes web pages dynamic and interactive.
<script type="text/javascript">
JavaScript code here.
</script>
Script tags may also reference external JavaScript files.<script type="text/javascript" src="myJsFile.js"></script>
// Use two slashes for single line commenting
/**
Use a slash and two asterisks
for multi-line commenting
**/
document.getElementById('student').innerHTML = 'John Doe';
alert('JavaScript alert message');
console.log('JavaScript console message');
1005
45.75
String - Can be enclosed in single or double quotes
"Hello World"
'JavaScript is awesome!'
Boolean - only two possible values
true
false
var varName;
var number1 = 1;
var number2 = 3;
var sum = number1 + number2;
var stringVariable = 'Hello';
(+ ) Addition
(- ) Subtraction
(* ) Multiplication
(/ ) Division
5 + 6
9 - 2
12 / 6
6 * 4
(5 - 3) * 5
Assignment and Concatenation(= ) Assignment Operator
(+ ) Concatenate Values (when not numeric)
var x = 12;
var name = 'John' + ' ' + 'Doe';
if(grade_level > 8){
console.log('High School');
}else{
console.log('Not High School');
}
(== ) Equality
(!= ) Inequality
(> ) Greater Than
(>= ) Greater Than or Equal
(< ) Less Than
(<= ) Less Than or Equal
( && ) And
(|| ) Or
( ! ) Not
if(grade_level > 8 && gender == 'M'){
console.log('Eight Grade Male');
}
if(grade_level == 6 || grade_level == 7 || grade_level == 8){
console.log('Middle School Student');
}
if(!booleanVariable){
console.log('boolean value is false');
}
function changeName(){
document.getElementById('name').innerHTML = 'Jane Doe';
}
changeName(); //invoke the changeName function
A function that returns a value
function addNumbers(a,b){
var result = a + b;
return result;
}
addNumbers(1,2); //invoke the function
var x = addNumbers(1,2); //invoke the function and set the result as the value of a variable (x)
console.log(addNumbers(1,2)); //invoke the function and log the result
//create an array and assign its value to the variable courses
var courses = ["Math","Language Arts","Science"];
//add an element to the end of the array using the .push() method
courses.push("Social Studies");
//Arrays use a zero-based indexing system
courses[0]; //Retrieves the value at index 0: Math
courses[2] = "Art"; //Changes the value at index 2 from Science to Art
//remove the last element from the array using the .pop() method
courses.pop();
Objects have multiple properties (a.k.a keys). Each property has a value.//Create an object and assign it as the value of a variable (student)
var student = {
"last_name":"Jones",
"first_name":"Angela",
"dob":"10/12/2002",
"grade_level":11
};
//Object properties can be referenced using dot notation
console.log(student.dob); //Log the dob property of the student object
student.grade_level = 12; //Change the value of the grade_level property
student.gender = 'M'; //Create a property (gender) on the student object and set the value to 'M'
//Object properties can also be referenced using bracket notation
console.log(student['dob']);
student['grade_level'] = 12;
student['gender'] = 'M';
Property values can also be other complex types (arrays, objects, functions)
var student = {
"last_name":"McCallister",
"first_name":"Kevin",
"activities":["Baseball","Soccer","Chess Club"],
"guardian":{
"last_name":"McCallister"
"first_name":"Kate",
"email":"kmccallister@gmail.com"
},
"getLastfirst":function(){
//use the this keyword to refer to the object
return this.last_name + ', ' + this.first_name;
}
}
console.log(student.activities[0]); //Log the first activity in the student's activities array
console.log(student.guardian.email); //Log the email property of the student's guardian object
console.log(student.getLastfirst()); //Log value returned by the getLastFirst property (a function)
//Loop through the numbers 1 - 10 and log them to the console
for (var i = 1; i <= 10; i++){
console.log(i);
}
forEach()
var nums = [2,4,7,9];
//iterate through each number in the nums array and log the square
nums.forEach(function(curNum){
console.log(curNum * curNum);
});
Iterating through an object
var grades = {
"Q1":"A-",
"Q2":"B",
"Q3":"B+",
"Q4":"A-"
};
//iterate through each key(property) of the grades object and display the data
//in the line below Object.keys(grades) gets an array of keys from the grades object - ["Q1", "Q2", "Q3", "Q4"]
Object.keys(grades).forEach(function(key) {
console.log(key + 'Grade: ' + grades[key]);
});
$j(selector).function();
Selector | Example | Selects |
---|---|---|
#id | $j("#lastname") | The element with id="lastname" |
.class | $j(".intro") | All elements with class="intro" |
.class,.class | $j(".intro,.demo") | All elements with the class "intro" or "demo" |
element | $j("p") | All <p> elements |
el1,el2,el3 | $j("h1,div,p") | All <h1>, <div> and <p> elements |
parent descendant | $j("div p") | All <p> elements that are descendants of a <div> element |
:first | $j("p:first") | The first <p> element |
:last | $j("p:last") | The last <p> element |
:even | $j("tr:even") | All even <tr> elements |
:odd | $j("tr:odd") | All odd <tr> elements |
:eq(index) | $j("ul li:eq(3)") | The fourth element in a list (index starts at 0) |
:gt(no) | $j("ul li:gt(3)") | List elements with an index greater than 3 |
:lt(no) | $j("ul li:lt(3)") | List elements with an index less than 3 |
:not(selector) | $j("input:not(:empty)") | All input elements that are not empty |
:contains(text) | $j(":contains('Hello')") | All elements which contains the text "Hello" |
:hidden | $j("p:hidden") | All hidden <p> elements |
:visible | $j("table:visible") | All visible tables |
[attribute] | $j("[href]") | All elements with a href attribute |
[attribute=value] | $j("[href='default.htm']") | All elements with a href attribute value equal to "default.htm" |
[attribute^=value] | $j("[title^='Tom']") | All elements with a title attribute value starting with "Tom" |
[attribute*=value] | $j("[title*='hello']") | All elements with a title attribute value containing the word "hello" |
:checkbox | $j(":checkbox") | All input elements with type="checkbox" |
:checked | $j(":checked") | All checked input elements |
<div id="selectorTestDiv">
<div id="testDiv">
<h3>Div (id="testDiv")</h3>
<span>Span 1</span>
<span>Span 2</span>
<span>Span 3</span>
<span class="specialSpan">Span 4 (class="specialSpan")</span>
<span class="specialSpan">Span 5 (class="specialSpan")</span>
</div>
<span> A span not contained in the testDiv. </span>
<table>
<tr><th>Col 1</th><th>Col 2</th><th>Col 2</th></tr>
<tr><td>1:1</td><td>1:2</td><td>1:3</td></tr>
<tr><td>2:1</td><td>2:2</td><td>2:3</td></tr>
<tr><td>3:1</td><td>3:2</td><td>3:3</td></tr>
<tr><td>4:1</td><td>4:2</td><td>4:3</td></tr>
</table>
</div>
Col 1 | Col 2 | Col 2 |
---|---|---|
1:1 | 1:2 | 1:3 |
2:1 | 2:2 | 2:3 |
3:1 | 3:2 | 3:3 |
4:1 | 4:2 | 4:3 |
//Generate an alert when the page is finished loading
$j(document).ready(function(){
alert('ready');
});
val() - Retrieve or set the value of an input.
//log the value of an element where id="gender"
console.log($j('#gender').val());
//set the value of an element where id="gender"
$j('#gender').val('F');
html() - Retrieve or set the innerHTML of an element.
//set the value of a variable to the contents of an element where id="studentName"
var name = $j('#studentName').html();
//set the contents of an element where id = "studentName"
$j('#studentName').html('John Doe');
show() and hide() - Show or hide an element.
//hide any element with class="conditional"
$j('.conditional').hide();
//show any element with class="conditional"
$j('.conditional').show();
click() - Known as an event listener. Run JavaScript when an element has been clicked//show elements with a class="additionalInfo" when a target button has been clicked
$j('#showInfoBtn').click(function(){
$j('.additionalInfo').show();
});
change() - Event listener for the change of an input value
//alert the user to enter a last name if the field is emptied
$j('#last_name').change(function(){
if($j('#last_name').val() == ''){
alert('Please enter a last name');
}
});
before(), after(), prepend(), append() - Insert content relative to a DOM element.
//assume we have the following element in our DOM
//<div id="targetElement">Original Div Contents</div>
//before() places content before a matching element
$j('#targetElement').before('Content Before');
//Result - Content Before<div id="targetElement">Original Div Contents</div>
//prepend() places content inside a matching element before the current contents
$j('#targetElement').prepend('Prepended Content ');
//Result - <div id="targetElement">Prepended Content Original Div Contents</div>
//append() places content inside a matching element after the current contents
$j('#targetElement').append(' Appended Content');
//Result - <div id="targetElement">Original Div Contents Appended Content</div>
//after() places content after a matching element
$j('#targetElement').after('Content After');
//Result - <div id="targetElement">Original Div Contents</div>Content After
clone() - Create a copy of an element in the DOM.
//duplicate a div by cloning it and inserting it into the DOM
var newDiv = $j('#myDiv').clone();
$j('#myDiv').after(newDiv);
remove() - Remove content from the DOM.
//remove the last row from a table
$j('#myTable tr:last').remove();
on() - Add event listeners for elements that may not yet exist when the DOM is ready$j('body').on('click','.targetElementClass', function(){
//handle click event
});
attr() - Get or set an attribute for an element
<div id="statusDiv" data-status="current">Div Contents</div>
//Log the data-status attribute of an element
console.log($j('#statusDiv').attr('data-status'));
//Set the data-status attribute of an element
$j('#statusDiv').attr('data-status','expired')
each() - jQuery forEach Loop
//Array of student objects
var students = [{"name":"Sally Juarez","grade":5},{"name":"Elise Marks","grade":7}];
//Loop through values in the students array, and log each value
$j(students).each(function(){
//The current value is referred to in the loop using the "this" keyword
console.log(this);
});
//Loop through rows in a table, and log the contents of the first td
$j('#myTable tr').each(function(){
//In this case, wrap the "this" keyword in $j() so jQuery functions can follow
console.log($j(this).find('td:first').html());
});
- "I'm listening for a change." | |
Make me disappear. |
|
Function | Description | Example | Code Explained |
load(url) | Load contents from another page (url) into a target container. |
$j('#containerId').load('anotherPage.html',function(){ alert('loaded'); }): |
Load the contents of anotherPage.html into an element with an id of "containerId". Once the content has been loaded, alert the user. |
serialize() | Encode a set of form elements as a string for submission. |
var formData = $j('#myForm').serialize(); |
Store string representation of data from a form with an id of "myForm" into a variable named formData. |
post(url, data, callback function) |
Load data from the server using a HTTP POST request.
|
$j.post('otherPage.html', $j('#myForm').serialize(),function(data){ alert(data); }); |
Submit the data in a form with an id of "myform" to otherPage.html. After receiving a response from otherPage.html, display an alert with the response text. |
<script type="text/javascript">
//Require the Angular JS framework on the page
require(['angular','components/shared/index'], function (angular) {
//Create an application (demoApp) and store it in a variable (myApp)
var myApp = angular.module('demoApp', ['powerSchoolModule']);
//Create a controller (demoAppCtrl) to house the application logic
myApp.controller('demoAppCtrl', function($scope) {
});
//Associate our application with the document
angular.bootstrap(document, ['demoApp']);
});
</script>
<script type="text/javascript">
require(['angular','components/shared/index'], function (angular) {
var myApp = angular.module('demoApp', ['powerSchoolModule']);
myApp.controller('demoAppCtrl', function($scope) {
$scope.userName = "Fred";
});
angular.bootstrap(document, ['demoApp']);
});
</script>
<body>
<div ng-controller="demoAppCtrl">
<input type="text" ng-model="userName" />
<div>{{userName}}</div>
<div ng-bind="userName"></div>
</div>
</body>
<div>
<input ng-model="newStudent.name" placeholder="Name" />
<input ng-model="newStudent.grade_level" placeholder="Grade Level">
<button ng-click="addStudent()" ng-disabled="invalidNew()">Add Student</button>
</div>
<div>
Grade Filter <input ng-model="selectedGrade" placeholder="Blank For Any" />
</div>
<table>
<tr>
<th>Name</th>
<th>Grade Level</th>
</tr>
<tr ng-repeat="student in students" ng-show="showStudent(student)">
<td>{{student.name}}</td>
<td>{{student.grade_level}}</td>
</tr>
</table>
Controller
myApp.controller('demoAppCtrl', function($scope) {
//initialize $scope properties
$scope.newStudent = {};
$scope.selectedGrade = '';
$scope.students = [
{"name":"James","grade_level":'8'},
{"name":"Susan","grade_level":'11'}
];
//Add the newStudent object to the students array and reset the newStudent value to an empty object
$scope.addStudent = function(){
$scope.students.push($scope.newStudent);
$scope.newStudent = {};
};
//Determine if the newStudent object is invalid (blank name or invalid grade level)
$scope.invalidNew = function(){
if($scope.newStudent.name == ''){
return true;
}
var grade = Number($scope.newStudent.grade_level);
if(grade > -5 && grade < 13){
return false
}else{
return true;
}
};
//Determine if a student should be visible based on the selected grade
$scope.showStudent = function(student){
return ($scope.selectedGrade == '' || student.grade_level == $scope.selectedGrade);
};
});
Name | Grade Level |
---|---|
{{student.name}} | {{student.grade_level}} |
<div style="display:inline-block;width:20em;border:1px solid black" class="center">
<H2 style="background-color:silver;margin:0px">
{{student.name}}
</H2>
Grade {{student.grade_level}}
</div>
The custom directive - The Angular JS code to create a directive named studentTile
myApp.directive("studentTile", function (){
return {
scope: {student: "="},
templateUrl: "studentTemplate.html"
}
});
The scope property allows us to provide a student object to each instance of our directive.<H3>Students</H3>
<span ng-repeat="stu in students">
<student-tile student="stu"></student-tile>
</span>
A student object is passed to the directive as an attribute.
//This controller will depend upon the Angular JS $http service.
//$http is added to the controller function parameters. This is called dependency injection.
myApp.controller('demoAppCtrl', function($scope, $http) {
$http({
"url": "someUrl",
"method": "GET or POST",
"params": "parameters for GET (object)",
"data": "data for POST (object)"
}).then(function successCallback(response){
//code to run if request succeeds
}, function errorCallback(response){
//code to run if request fails
});
});
studentCount.html
~[tlist_sql;
SELECT count(*)
FROM students
WHERE grade_level = ~(gpv.grade)
;]~(total)[/tlist_sql]
View
Select a grade level to find the student total
<select ng-model="grade_level" ng-change="getGradeCount()">
<option value="0">0</option>
<option value="1">1</option>
...
</select>
<b>{{gradeCount}}</b>
<span ng-if="gradeCount"> Students in Grade {{grade_level}}</span>
Controller
$scope.getGradeCount = function(){
$http({
"url": "studentCount.html",
"method": "GET",
"params": {"grade":$scope.grade_level}
})
.then(function(response){
$scope.gradeCount = response.data;
});
};
$scope.userName = "Fred";
$scope.numericValue = 15587.58886;
$scope.courses = [
{"name":"Biology","department":"Sci"},
{"name":"Algebra","department":"Mat"},
{"name":"Trigonometry","department":"Mat"},
{"name":"Literature","department":"Eng"}
];
<b>No Filter</b> - {{userName}} <br/>
<b>lowercase</b> - {{userName | lowercase}} <br/>
<b>uppercase</b> - {{userName | uppercase}}<br/>
<b>No Filter</b> - {{numericValue}} <br/>
<b>number : 1</b> - {{numericValue | number : 1}} <br/>
<b>currency</b> - {{numericValue | currency}}<br/><br/>
<p>ng-repeat="course in courses | <b>orderBy:'name'</b> "</p>
<table>
<tr><th>course</th><th>Department</th></tr>
<tr ng-repeat="course in courses | orderBy:'name'">
<td>{{course.name}}</td>
<td>{{course.department}}</td>
</tr>
</table>
<p>ng-repeat="course in courses | <b>filter:courseSearch</b>"</p>
<div class="center"><input ng-model="courseSearch" placeholder="course Search"/></div>
<table>
<tr><th>course</th><th>Department</th></tr>
<tr ng-repeat="course in courses | filter:courseSearch">
<td>{{course.name}}</td>
<td>{{course.department}}</td>
</tr>
</table>
ng-repeat="course in courses | orderBy:'name' "
course | Department |
---|---|
{{course.name}} | {{course.department}} |
ng-repeat="course in courses | filter:courseSearch"
course | Department |
---|---|
{{course.name}} | {{course.department}} |
define(['angular'], function(angular) {
var myApp = angular.module('gradeModule', []);
myApp.service('gradeService', function(){
this.getStudentGradeLevelName = function(student){
if(Number(student.grade_level) < 6){
return "Elementary";
}else if(Number(student.grade_level) < 9){
return "Middle";
}else if(Number(student.grade_level) < 13){
return "High";
}else if(Number(student.grade_level) == 99){
return "Graduated";
}else{
return "Unknown";
}
}
});
});
Module/Controller
Must include the path to the service so it can be included in the module
require(['angular','components/shared/index','/path_to_file.../gradeService.js'],
function (angular) {
//Include the name of the desired module in the application dependencies
var myApp = angular.module('demoApp', ['powerSchoolModule','gradeModule']);
//Include the gradeService as a dependency for the controller
myApp.controller('demoAppCtrl', function($scope, gradeService) {
$scope.honorRollStudents = [
{"name":"Ben Johnson","grade_level":"12"},
{"name":"Louise Wilcox","grade_level":"1"},
{"name":"Renly Inman","grade_level":"4"},
{"name":"Alissa Smith","grade_level":"10"},
{"name":"Lena Gardner","grade_level":"7"},
{"name":"Lester Millis","grade_level":"99"},
{"name":"Alfred Caleston","grade_level":"20"}
];
$scope.gradeName = function(student){
//Because we've included the gradeService
return gradeService.getStudentGradeLevelName(student);
};
});
});
View
<table>
<tr><th>Student</th><th>Grade Level</th><th>Grade Desc</th></tr>
<tr ng-repeat="student in honorRollStudents">
<td>{{student.name}}</td>
<td>{{student.grade_level}}</td>
<td>{{gradeName(student)}}</td>
</tr>
</table>
Student | Grade Level | Grade Desc |
---|---|---|
{{student.name}} | {{student.grade_level}} | {{gradeName(student)}} |
define(['angular'], function(angular) {
angular.module("powerQueryModule",[])
.service("pqService",function($http, $q){
//query - the name of the PowerQuery
//data - JavaScript Object including any parameters that must be passed to the query
this.getPQResults = function(query, data){
var deferredResponse = $q.defer();
$http({
url: '/ws/schema/query/' + query,
method:'POST',
data: data || {},
params: {"pagesize":0},
headers: {
'Accept': 'application/json',
"Content-Type": "application/json"
}
})
.then(function(response){
deferredResponse.resolve(response.data.record || []);
});
return deferredResponse.promise;
};
});
});
Put the service to use
require(['angular','components/shared/index','/path_to_file.../pqService.js'], function (angular) {
var myApp = angular.module('demoApp', ['powerSchoolModule','powerQueryModule']);
myApp.controller('demoAppCtrl', function($scope, $http, pqService) {
pqService.getPQResults('com.mba.psugDemo.schoolData.enrollment').then(function(response){
//Response will be an array of results
//View the console to see an example
});
});
});