There's something wrong with my shunting yards algorithms - javascript

I got some problem on working with shunting yards algorithm : I use it to parse an equation then use that equation to draw an graph, but somehow it's parsing x^2-0.5x+1 to -0.5x+1, is there anyways to fix that
Here the link to the test code : https://codepen.io/Inasaya-Flanderin/pen/ExbbgQm
This is the code part:
function parse(rpn) {
let stack = [];
Array.from(rpn).forEach((t) => {
let tr = null;
if (isNumber(t) || isVariable(t)) {
tr = genNode(t, false);
} else {
if (Object.keys(binary_functions).includes(t)) {
tr = genNode(binary_functions[t], true, false);
let a = stack.pop();
let b = stack.pop();
if (typeof a === 'number') {
tr.right = genNode(a, false);
} else {
tr.right = a;
}
if (typeof b === 'number') {
tr.left = genNode(b, false);
} else {
tr.left = b;
}
} else if (Object.keys(unary_functions).includes(t)) {
tr = genNode(unary_functions[t]);
a = stack.pop();
if (typeof a === 'number') {
tr.left = genNode(a, false);
} else {
tr.left = a;
}
}
}
tr.name = t;
stack.push(tr);
});
return stack.pop();
}
function eval(tree) {
if (tree.func) {
if (tree.unary) {
return tree.val.eval(eval(tree.left));
} else {
return tree.val.eval(eval(tree.left), eval(tree.right));
}
} else {
if (constant_names.includes(tree.val)) {
return constants[tree.val];
} else if (varnames.includes(tree.val)) {
return variables[tree.val];
} else {
return tree.val;
}
}
}

Related

Uncaught Error: cannot call methods on prior to initialization; attempted to call method

I have a javascript method in a partial view .Net 6 MVC like this: After upgrading to JQuery 3.6.1 and JQuery UI 1.13.2. I am getting errors like:
Uncaught Error: cannot call methods on NumericBox prior to initialization; attempted to call method 'isNumeric'. Please suggest. Thanks.
function CompareDialog() {
var aReleased;
$(".weighting-total").NumericBox("setValue", $(".weighting").NumericBoxSum());
}
The javascript for the NumericBox and NumericBoxSum:
$.widget("Data.NumericBox", {
options: {
allowReservedValues: undefined,
readOnly: undefined,
decimalPlaces: undefined,
showZero: undefined,
allowNegative: undefined,
thousandSeperator: undefined
},
_create: function () {
this._super();
var that = this;
// Option: Allow Reserved Values
if (this.options.allowReservedValues == undefined) {
if (this.element.data("allow-reserved-values") != undefined) {
this.options.allowReservedValues = JSON.parse(this.element.data("allow-reserved-values").toLowerCase());
}
else {
this.options.allowReservedValues = false;
}
}
// Option: Read Only
if (this.options.readOnly != undefined) {
this.element.prop("readonly", this.options.readOnly);
}
// Option: Decimal Places
if (this.options.decimalPlaces == undefined) {
if (this.element.data("decimal-places") != undefined) {
this.options.decimalPlaces = parseInt(this.element.data("decimal-places"));
}
else {
this.options.decimalPlaces = 0;
}
}
// Option: Show Zero
if (this.options.showZero == undefined) {
if (this.element.data("show-zero") != undefined) {
this.options.showZero = JSON.parse(this.element.data("show-zero").toLowerCase());
}
else {
this.options.showZero = true;
}
}
// Option: Allow Negative
if (this.options.allowNegative == undefined) {
if (this.element.data("allow-negative") != undefined) {
this.options.allowNegative = JSON.parse(this.element.data("allow-negative").toLowerCase());
}
else {
this.options.allowNegative = false;
}
}
// Option: Thousand Seperator
if (this.options.thousandSeperator == undefined) {
if (this.element.data("thousand-seperator") != undefined) {
this.options.thousandSeperator = this.element.data("thousand-seperator");
}
else {
this.options.thousandSeperator = ",";
}
}
// Set client-side validation to ignore N/Avail and N/Appl values
if ($.validator.defaults.ignore.indexOf(".fd-not-available") < 0) {
$.validator.setDefaults({
ignore: $.validator.defaults.ignore + ",.fd-not-available,.fd-not-applicable"
});
}
// Define validation for hyphens
if (this.options.allowNegative) {
if ($.validator.methods["val-hyphen"] === undefined) {
$.validator.addMethod("val-hyphen", function (value, element) {
var message = $(element).data("val-number");
if (value == "-") {
return false;
}
return true;
}, $.validator.format("{0}"));
}
this.element.attr("val-hyphen", this.element.data("val-number"));
}
// Handle paste
this.element.on("paste", function (event) {
if ($(this).hasClass("fd-not-available") || $(this).hasClass("fd-not-applicable")) {
$(this).val("").removeClass("fd-not-available fd-not-applicable");
}
});
// Handle clearing of textbox
this.element.on("input", function (event) {
if ($(this).val() == "") {
$(this).removeClass("fd-not-available fd-not-applicable");
}
});
this.element.keydown(function (event) {
if (that.isReserved()) {
if (!$(this).prop("readonly") && (event.which == 8 || event.which == 46)) {
$(this).val("").removeClass("fd-not-available fd-not-applicable").select();
event.preventDefault();
}
}
});
this.element.keypress(function (event) {
if (that.element.prop("readonly")) {
event.preventDefault();
return;
}
if (event.which == 78 || event.which == 110) { // N
if (that.options.allowReservedValues) {
that.setReserved(ReservedValue.NotAvailable);
$(this).change();
}
event.preventDefault();
return;
}
if (event.which == 80 || event.which == 112) { // P
if (that.options.allowReservedValues) {
that.setReserved(ReservedValue.NotApplicable);
$(this).change();
}
event.preventDefault();
return;
}
if (event.which == 45) { // -
if (!that.options.allowNegative) {
event.preventDefault();
return;
}
if (that.isReserved()) {
that.setValue("");
}
that.refresh();
return;
}
if (event.which == 46) { // .
if (that.options.decimalPlaces == 0) {
event.preventDefault();
return;
}
if (that.isReserved()) {
that.setValue("");
}
that.refresh();
return;
}
if (event.which >= 48 && event.which <= 57) { // 0 - 9
if (that.isReserved()) {
$(this).val("");
}
if (that.isReserved()) {
that.setValue("");
}
that.refresh();
return;
}
event.preventDefault();
});
this.element.focusin(function (event) {
var value = that._internalFormat($(this).val());
$(this).val(value);
});
this.element.focusout(function (event) {
var value = that._externalFormat($(this).val());
$(this).val(value);
});
this.element.val(this._externalFormat(this.element.val()));
this.refresh();
},
_externalFormat: function (value) {
if ($.isNumeric(value)) {
if (parseFloat(value) == 0 && !this.options.showZero) {
return "";
}
else if (!ReservedValue.isReserved(value)) {
var signPart = value > -1 && value < 0 ? "-" : ""; // Required: In the following statement parseInt removes the sign for small negative numbers
var integerPart = parseInt(numeral(value).format("0" + (0).toFixed(this.options.decimalPlaces).substr(1)));
var fractionalPart = Big(value).minus(Big(integerPart)).abs();
var display = signPart + numeral(integerPart).format("0" + this.options.thousandSeperator + "0") +
fractionalPart.toFixed(this.options.decimalPlaces).substr(1);
return display;
}
}
return value;
},
_internalFormat: function (value) {
try {
value = value.replace(/,/g, "");
if ($.isNumeric(value)) {
if (this.options.decimalPlaces == 0) {
value = parseInt(value);
}
else {
value = Big(value).format("0" + (0).toFixed(this.options.decimalPlaces).substr(1)).toString();
}
}
return value;
}
catch (e) {
return value;
}
},
refresh: function () {
var value = this._internalFormat(this.element.val());
if (this.options.allowReservedValues) {
if (value == ReservedValue.NotAvailable) {
this.element.val(ReservedValue.text(value)).removeClass("fd-not-applicable").addClass("fd-not-available");
}
else if (value == ReservedValue.NotApplicable) {
this.element.val(ReservedValue.text(value)).removeClass("fd-not-available").addClass("fd-not-applicable");
}
else {
if (this.element.hasClass("fd-not-available") || this.element.hasClass("fd-not-applicable")) {
this.element.removeClass("fd-not-available fd-not-applicable");
}
}
}
return this;
},
setValue: function (value) {
this.element.val(this._externalFormat(value));
this.refresh();
},
getValue: function () {
return this._internalFormat(this.element.val());
},
isNumeric: function (includeReservedValues) {
includeReservedValues = includeReservedValues === undefined ? false : includeReservedValues;
if (!includeReservedValues && this.isReserved()) {
return false;
}
else {
return $.isNumeric(this.getValue());
}
},
isReserved: function (resval) {
var value = ReservedValue.parse(this._internalFormat(this.element.val()));
if (resval === undefined) {
return ReservedValue.isReserved(value);
}
else {
return value == resval;
}
},
setReserved: function (resval) {
this.element.val(resval).valid();
this.refresh();
},
getReserved: function () {
return ReservedValue.parse(this._internalFormat(this.element.val()));
}
});
$.fn.NumericBoxSum = function (blankIfNoNumerics) {
var NumericCount = 0;
var sum = 0.0;
blankIfNoNumerics = blankIfNoNumerics === undefined ? false : blankIfNoNumerics;
this.each(function () {
if ($(this).NumericBox("isNumeric")) {
sum += parseFloat($(this).NumericBox("getValue"));
NumericCount++;
}
});
if (NumericCount == 0 && blankIfNoNumerics) {
sum = "";
}
return sum;
};

How to check if 2 strings are equal in JavaScript?

I'm a beginner in JS and trying to sort some cars by their model. The models are sorted by ranking in this order (Mercedes, BMW, Jeep, Nissan). I would like it to be case-insensitive. I went about it by creating a variable for creating the desired rankings.
var modelRanking = function(car) {
if (car.model.toLowerCase() === 'mercedes') {
return 1;
} else if (car.model.toLowerCase() === 'bmw') {
return 2;
} else if (car.model.toLowerCase() === 'jeep') {
return 3;
} else if (car.model.toLowerCase() === 'nissan') {
return 4;
} else {
return 5;
}
}
function modelComparator(car1, car2) {
if (car1.modelRanking < car2.modelRanking) {
return true;
} else if (car1.modelRanking > car2.modelRanking) {
return false;
} else if (car1.modelRanking == car2.modelRanking) {
return yearComparator(car1, car2);
}
}
However the modelRanking is always returning 5.
Instead of car1.modelRanking, use modelRanking(car1) because modelRanking is a function in global scope, not a property of car1.
function modelComparator(car1, car2) {
if (modelRanking(car1) < modelRanking(car2)) {
return true;
} else if (modelRanking(car1) > modelRanking(car2)) {
return false;
} else if (modelRanking(car1) == modelRanking(car2)) {
return yearComparator(car1, car2);
}
}

Why object property undefined in another method from the same object but not undefined in other? [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 8 months ago.
Ok, so I've been struggling with something I think it's pretty simple. Not sure if it's the Babel compiler or what. So I've got this class:
export default class animateFormClass {
constructor(formSelector, buttonElement = null, currentCard = null, prevCard = null, nextCard = null) {
this.form = document.querySelector(formSelector);
this.direction = 'forward';
this.progressBar = document.getElementById('progressbar');
this.opacity = this.opacityLeft = 0;
this.buttonElement = buttonElement;
this.currentCard = currentCard;
this.prevCard = prevCard;
this.nextCard = nextCard;
}
animateForm() {
if (this.direction === 'forward') {
if (this.nextCard !== null) {
this.fadeOut = setInterval(this.fadeOutAnimation, 10);
this.updateProgressBar;
}
} else if (this.direction === 'back') {
if (this.prevCard !== null) {
this.fadeOut = setInterval(this.fadeOutAnimation, 10);
this.updateProgressBar;
}
}
}
fadeOutAnimation() {
this.opacity = this.opacity - 0.05;
console.log(this.opacity, this.currentCard);
if (this.opacity >= 0) {
this.currentCard.style.opacity = this.opacity;
} else {
this.currentCard.classList.add('d-none');
this.fadeIn = setInterval(this.fadeInAnimation, 10);
clearInterval(this.fadeOut);
}
}
fadeInAnimation() {
this.opacityLeft = this.opacityLeft + 0.1;
let cardElement;
if (this.direction === 'forward') {
cardElement = this.nextCard;
} else if (this.direction === 'back') {
cardElement = this.prevCard;
}
cardElement.classList.remove('d-none');
if (this.opacityLeft <= 1) {
cardElement.style.opacity = this.opacityLeft;
} else {
clearInterval(this.fadeIn);
}
}
updateProgressBar() {
let activeElement = this.progressBar.querySelector('.active');
let nextListElement = activeElement.nextElementSibling;
let prevListElement = activeElement.previousElementSibling;
if (this.direction === 'forward') {
if (nextListElement !== null) {
activeElement.classList.remove('active');
activeElement.classList.add('step-completed');
nextListElement.classList.add('active');
}
} else if (this.direction === 'back') {
if (prevListElement !== null) {
activeElement.classList.remove('active');
prevListElement.classList.remove('step-completed');
prevListElement.classList.add('active');
}
}
}
}
and from another file I'm importing the class like this:
import animateFormClass from './animateForm';
Ok so in this file I've got some code in which I update some of the object properties but in the animateForm() method the properties seem to be OK BUT when those same object properties are used by the other method called fadeOutAnimation() I've got this message of undefined in the this.currentCard property.
Here's the code in which I make the class instance:
if (document.getElementById('register')) {
let animate = new animateFormClass('#register');
let currentCard, prevCard, nextCard;
document.getElementById('register').addEventListener('click', function(e) {
if (e.target.classList.contains('next')) {
animate.direction = 'forward';
animate.currentCard = e.target.closest('fieldset');
animate.nextCard = animate.currentCard.nextElementSibling;
animate.animateForm();
} else if (e.target.classList.contains('prev')) {
animate.direction = 'back';
animate.animateForm(e.target);
}
});
}
I get the error when the animate.animateForm() method is called. My environment is working on a PHP web app using Laravel and using the watch task that Laravel has out of the box.
EDIT:
Thank you for your help, I was able to fix it. If anyone was wondering, I changed all the methods of the class as properties and used the arrow function syntax. So thanks again!!!
When you're doing setInterval(this.fadeOutAnimation, 10), 'this' inside 'fadeOutAnimation' is binded by window. Use setInterval(() => { this.fadeOutAnimation() }, 10); It preserves 'this' context.
Thank you for your help, I was able to fix it. If anyone was wondering, I changed all the methods of the class as properties and used the arrow function syntax. So thanks again!!!
Here's the new code:
export default class animateFormClass {
constructor(formSelector) {
this.form = document.querySelector(formSelector);
this.direction = null;
this.progressBar = document.getElementById('progressbar');
this.opacity = this.opacityLeft = 0;
this.buttonElement = null;
this.currentCard = null;
this.prevCard = null;
this.nextCard = null;
this.animateForm = (buttonElement) => {
this.buttonElement = buttonElement;
this.currentCard = this.buttonElement.closest('fieldset');
this.nextCard = this.currentCard.nextElementSibling;
this.prevCard = this.currentCard.previousElementSibling;
if(this.direction === 'forward') {
if(this.nextCard !== null) {
this.fadeOut = setInterval(() => { this.fadeOutAnimation() }, 10);
this.updateProgressBar();
}
}
else if(this.direction === 'back') {
if(this.prevCard !== null) {
this.fadeOut = setInterval(() => { this.fadeOutAnimation() }, 10);
this.updateProgressBar();
}
}
}
this.fadeOutAnimation = () => {
this.opacity = this.opacity - 0.05;
if(this.opacity >= 0) {
this.currentCard.style.opacity = this.opacity;
}
else {
this.currentCard.classList.add('d-none');
this.fadeIn = setInterval(this.fadeInAnimation, 10);
clearInterval(this.fadeOut);
}
}
this.fadeInAnimation = () => {
this.opacityLeft = this.opacityLeft + 0.1;
let cardElement;
if(this.direction === 'forward') {
cardElement = this.nextCard;
}
else if(this.direction === 'back') {
cardElement = this.prevCard;
}
cardElement.classList.remove('d-none');
if(this.opacityLeft <= 1) {
cardElement.style.opacity = this.opacityLeft;
}
else {
clearInterval(this.fadeIn);
}
}
this.updateProgressBar = () => {
let activeElement = this.progressBar.querySelector('.active');
let nextListElement = activeElement.nextElementSibling;
let prevListElement = activeElement.previousElementSibling;
if(this.direction === 'forward') {
if(nextListElement !== null) {
activeElement.classList.remove('active');
activeElement.classList.add('step-completed');
nextListElement.classList.add('active');
}
}
else if(this.direction === 'back') {
if(prevListElement !== null) {
activeElement.classList.remove('active');
prevListElement.classList.remove('step-completed');
prevListElement.classList.add('active');
}
}
}
}
}

up/down arrow scroll not working

up/down arrow scroll not working in jquery scrolify plugin.I want to do the scroll with both page up/down button and in up/down arrow button click.
page up/down arrow working fine as I expect.up/down button click not scroll as page scroll
if(e.keyCode==33 ) { //working
if(index>0) {
if(atTop()) {
e.preventDefault();
index--;
//index, instant, callbacks
animateScroll(index,false,true);
}
}
} else if(e.keyCode==34) { //working
if(index<heights.length-1) {
if(atBottom()) {
e.preventDefault();
index++;
//index, instant, callbacks
animateScroll(index,false,true);
}
}
}
if(e.keyCode==38) { //not working
if(index>0) {
if(atTop()) {
e.preventDefault();
index--;
//index, instant, callbacks
animateScroll(index,false,true);
console.log('up arrow');
}
}
} else if(e.keyCode==40) { //not working
if(index<heights.length-1) {
if(atBottom()) {
e.preventDefault();
index++;
//index, instant, callbacks
animateScroll(index,false,true);
console.log('down arrow');
}
}
}
/*!
* jQuery Scrollify
* Version 1.0.5
*
* Requires:
* - jQuery 1.7 or higher
*
* https://github.com/lukehaas/Scrollify
*
* Copyright 2016, Luke Haas
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
If section being scrolled to is an interstitialSection and the last section on page
then value to scroll to is current position plus height of interstitialSection
*/
(function (global,factory) {
"use strict";
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], function($) {
return factory($, global, global.document);
});
} else if (typeof module === 'object' && module.exports) {
// Node/CommonJS
module.exports = function( root, jQuery ) {
if ( jQuery === undefined ) {
// require('jQuery') returns a factory that requires window to
// build a jQuery instance, we normalize how we use modules
// that require this pattern but the window provided is a noop
// if it's defined (how jquery works)
if ( typeof window !== 'undefined' ) {
jQuery = require('jquery');
} else {
jQuery = require('jquery')(root);
}
}
factory(jQuery, global, global.document);
return jQuery;
};
} else {
// Browser globals
factory(jQuery, global, global.document);
}
}(typeof window !== 'undefined' ? window : this, function ($, window, document, undefined) {
"use strict";
var heights = [],
names = [],
elements = [],
overflow = [],
index = 0,
currentIndex = 0,
interstitialIndex = 1,
hasLocation = false,
timeoutId,
timeoutId2,
$window = $(window),
top = $window.scrollTop(),
scrollable = false,
locked = false,
scrolled = false,
manualScroll,
swipeScroll,
util,
disabled = false,
scrollSamples = [],
scrollTime = new Date().getTime(),
firstLoad = true,
initialised = false,
wheelEvent = 'onwheel' in document ? 'wheel' : document.onmousewheel !== undefined ? 'mousewheel' : 'DOMMouseScroll',
settings = {
//section should be an identifier that is the same for each section
section: ".section",
//sectionName: "section-name",
interstitialSection: "",
easing: "easeOutExpo",
scrollSpeed: 500,
offset : 0,
scrollbars: true,
target:"html,body",
standardScrollElements: false,
setHeights: true,
overflowScroll:true,
before:function() {},
after:function() {},
afterResize:function() {},
afterRender:function() {}
};
function animateScroll(index,instant,callbacks) {
if(currentIndex===index) {
callbacks = false;
}
if(disabled===true) {
return true;
}
if(names[index]) {
scrollable = false;
if(callbacks) {
settings.before(index,elements);
}
interstitialIndex = 1;
if(settings.sectionName && !(firstLoad===true && index===0)) {
if(history.pushState) {
try {
history.replaceState(null, null, names[index]);
} catch (e) {
if(window.console) {
console.warn("Scrollify warning: This needs to be hosted on a server to manipulate the hash value.");
}
}
} else {
window.location.hash = names[index];
}
}
if(instant) {
$(settings.target).stop().scrollTop(heights[index]);
if(callbacks) {
settings.after(index,elements);
}
} else {
locked = true;
if( $().velocity ) {
$(settings.target).stop().velocity('scroll', {
duration: settings.scrollSpeed,
easing: settings.easing,
offset: heights[index],
mobileHA: false
});
} else {
$(settings.target).stop().animate({
scrollTop: heights[index]
}, settings.scrollSpeed,settings.easing);
}
if(window.location.hash.length && settings.sectionName && window.console) {
try {
if($(window.location.hash).length) {
console.warn("Scrollify warning: There are IDs on the page that match the hash value - this will cause the page to anchor.");
}
} catch (e) {
console.warn("Scrollify warning:", window.location.hash, "is not a valid jQuery expression.");
}
}
$(settings.target).promise().done(function(){
currentIndex = index;
locked = false;
firstLoad = false;
if(callbacks) {
settings.after(index,elements);
}
});
}
}
}
function isAccelerating(samples) {
function average(num) {
var sum = 0;
var lastElements = samples.slice(Math.max(samples.length - num, 1));
for(var i = 0; i < lastElements.length; i++){
sum += lastElements[i];
}
return Math.ceil(sum/num);
}
var avEnd = average(10);
var avMiddle = average(70);
if(avEnd >= avMiddle) {
return true;
} else {
return false;
}
}
$.scrollify = function(options) {
initialised = true;
$.easing['easeOutExpo'] = function(x, t, b, c, d) {
return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
};
manualScroll = {
/*handleMousedown:function() {
if(disabled===true) {
return true;
}
scrollable = false;
scrolled = false;
},*/
handleMouseup:function() {
if(disabled===true) {
return true;
}
scrollable = true;
if(scrolled) {
//instant,callbacks
manualScroll.calculateNearest(false,true);
}
},
handleScroll:function() {
if(disabled===true) {
return true;
}
if(timeoutId){
clearTimeout(timeoutId);
}
timeoutId = setTimeout(function(){
scrolled = f;
if(scrollable===false) {
return false;
}
scrollable = false;
//instant,callbacks
manualScroll.calculateNearest(false,false);
}, 200);
},
calculateNearest:function(instant,callbacks) {
top = $window.scrollTop();
var i =1,
max = heights.length,
closest = 0,
prev = Math.abs(heights[0] - top),
diff;
for(;i<max;i++) {
diff = Math.abs(heights[i] - top);
if(diff < prev) {
prev = diff;
closest = i;
}
}
if(atBottom() || atTop()) {
index = closest;
//index, instant, callbacks
animateScroll(closest,instant,callbacks);
}
},
/*wheel scroll*/
wheelHandler:function(e) {
if(disabled===true) {
return true;
} else if(settings.standardScrollElements) {
if($(e.target).is(settings.standardScrollElements) || $(e.target).closest(settings.standardScrollElements).length) {
return true;
}
}
if(!overflow[index]) {
e.preventDefault();
}
var currentScrollTime = new Date().getTime();
e = e || window.event;
var value = e.originalEvent.wheelDelta || -e.originalEvent.deltaY || -e.originalEvent.detail;
var delta = Math.max(-1, Math.min(1, value));
//delta = delta || -e.originalEvent.detail / 3 || e.originalEvent.wheelDelta / 120;
if(scrollSamples.length > 149){
scrollSamples.shift();
}
//scrollSamples.push(Math.abs(delta*10));
scrollSamples.push(Math.abs(value));
if((currentScrollTime-scrollTime) > 200){
scrollSamples = [];
}
scrollTime = currentScrollTime;
if(locked) {
return false;
}
if(delta<0) {
if(index<heights.length-1) {
if(atBottom()) {
if(isAccelerating(scrollSamples)) {
e.preventDefault();
index++;
locked = true;
//index, instant, callbacks
animateScroll(index,false,true);
} else {
return false;
}
}
}
} else if(delta>0) {
if(index>0) {
if(atTop()) {
if(isAccelerating(scrollSamples)) {
e.preventDefault();
index--;
locked = true;
//index, instant, callbacks
animateScroll(index,false,true);
} else {
return false
}
}
}
}
},
/*end of wheel*/
keyHandler:function(e) {
if(disabled===true) {
return true;
}
if(locked===true) {
return false;
}
if(e.keyCode==33 ) {
if(index>0) {
if(atTop()) {
e.preventDefault();
index--;
//index, instant, callbacks
animateScroll(index,false,true);
}
}
} else if(e.keyCode==34) {
if(index<heights.length-1) {
if(atBottom()) {
e.preventDefault();
index++;
//index, instant, callbacks
animateScroll(index,false,true);
}
}
}
if(e.keyCode==38) {
if(index>0) {
if(atTop()) {
e.preventDefault();
index--;
//index, instant, callbacks
animateScroll(index,false,true);
console.log('up arrow');
}
}
} else if(e.keyCode==40) {
if(index<heights.length-1) {
if(atBottom()) {
e.preventDefault();
index++;
//index, instant, callbacks
animateScroll(index,false,true);
console.log('down arrow');
}
}
}
/*home, end button testing*/
if(e.keyCode==35) {
for(index=6;index<1;index--)
{
console.log("worked on end button");
}
}
else if(e.keyCode==36) {
for(index=0;intex<1;index++)
{
console.log("worked on home button");
}
}
/*home,end button end*/
},
init:function() {
if(settings.scrollbars) {
$window.on('mousedown', manualScroll.handleMousedown);
$window.on('mouseup', manualScroll.handleMouseup);
$window.on('scroll', manualScroll.handleScroll);
} else {
$("body").css({"overflow":"hidden"});
}
$window.on(wheelEvent,manualScroll.wheelHandler);
$(document).bind(wheelEvent,manualScroll.wheelHandler);
$window.on('keydown', manualScroll.keyHandler);
}
};
swipeScroll = {
touches : {
"touchstart": {"y":-1,"x":-1},
"touchmove" : {"y":-1,"x":-1},
"touchend" : false,
"direction" : "undetermined"
},
options:{
"distance" : 30,
"timeGap" : 800,
"timeStamp" : new Date().getTime()
},
touchHandler: function(event) {
if(disabled===true) {
return true;
} else if(settings.standardScrollElements) {
if($(event.target).is(settings.standardScrollElements) || $(event.target).closest(settings.standardScrollElements).length) {
return true;
}
}
var touch;
if (typeof event !== 'undefined'){
if (typeof event.touches !== 'undefined') {
touch = event.touches[0];
switch (event.type) {
case 'touchstart':
swipeScroll.touches.touchstart.y = touch.pageY;
swipeScroll.touches.touchmove.y = -1;
swipeScroll.touches.touchstart.x = touch.pageX;
swipeScroll.touches.touchmove.x = -1;
swipeScroll.options.timeStamp = new Date().getTime();
swipeScroll.touches.touchend = false;
case 'touchmove':
swipeScroll.touches.touchmove.y = touch.pageY;
swipeScroll.touches.touchmove.x = touch.pageX;
if(swipeScroll.touches.touchstart.y!==swipeScroll.touches.touchmove.y && (Math.abs(swipeScroll.touches.touchstart.y-swipeScroll.touches.touchmove.y)>Math.abs(swipeScroll.touches.touchstart.x-swipeScroll.touches.touchmove.x))) {
//if(!overflow[index]) {
event.preventDefault();
//}
swipeScroll.touches.direction = "y";
if((swipeScroll.options.timeStamp+swipeScroll.options.timeGap)<(new Date().getTime()) && swipeScroll.touches.touchend == false) {
swipeScroll.touches.touchend = true;
if (swipeScroll.touches.touchstart.y > -1) {
if(Math.abs(swipeScroll.touches.touchmove.y-swipeScroll.touches.touchstart.y)>swipeScroll.options.distance) {
if(swipeScroll.touches.touchstart.y < swipeScroll.touches.touchmove.y) {
swipeScroll.up();
} else {
swipeScroll.down();
}
}
}
}
}
break;
case 'touchend':
if(swipeScroll.touches[event.type]===false) {
swipeScroll.touches[event.type] = true;
if (swipeScroll.touches.touchstart.y > -1 && swipeScroll.touches.touchmove.y > -1 && swipeScroll.touches.direction==="y") {
if(Math.abs(swipeScroll.touches.touchmove.y-swipeScroll.touches.touchstart.y)>swipeScroll.options.distance) {
if(swipeScroll.touches.touchstart.y < swipeScroll.touches.touchmove.y) {
swipeScroll.up();
} else {
swipeScroll.down();
}
}
swipeScroll.touches.touchstart.y = -1;
swipeScroll.touches.touchstart.x = -1;
swipeScroll.touches.direction = "undetermined";
}
}
default:
break;
}
}
}
},
down: function() {
if(index<=heights.length-1) {
if(atBottom() && index<heights.length-1) {
index++;
//index, instant, callbacks
animateScroll(index,false,true);
} else {
if(Math.floor(elements[index].height()/$window.height())>interstitialIndex) {
interstitialScroll(parseInt(heights[index])+($window.height()*interstitialIndex));
interstitialIndex += 1;
} else {
interstitialScroll(parseInt(heights[index])+(elements[index].height()-$window.height()));
}
}
}
},
up: function() {
if(index>=0) {
if(atTop() && index>0) {
index--;
//index, instant, callbacks
animateScroll(index,false,true);
} else {
if(interstitialIndex>2) {
interstitialIndex -= 1;
interstitialScroll(parseInt(heights[index])+($window.height()*interstitialIndex));
} else {
interstitialIndex = 1;
interstitialScroll(parseInt(heights[index]));
}
}
}
},
init: function() {
if (document.addEventListener) {
document.addEventListener('touchstart', swipeScroll.touchHandler, false);
document.addEventListener('touchmove', swipeScroll.touchHandler, false);
document.addEventListener('touchend', swipeScroll.touchHandler, false);
}
}
};
util = {
refresh:function(withCallback) {
clearTimeout(timeoutId2);
timeoutId2 = setTimeout(function() {
sizePanels();
calculatePositions(true);
if(withCallback) {
settings.afterResize();
}
},400);
},
handleUpdate:function() {
util.refresh(false);
},
handleResize:function() {
util.refresh(true);
}
};
settings = $.extend(settings, options);
sizePanels();
calculatePositions(false);
if(true===hasLocation) {
//index, instant, callbacks
animateScroll(index,false,true);
} else {
setTimeout(function() {
//instant,callbacks
manualScroll.calculateNearest(true,false);
},200);
}
if(heights.length) {
manualScroll.init();
swipeScroll.init();
$window.on("resize",util.handleResize);
if (document.addEventListener) {
window.addEventListener("orientationchange", util.handleResize, false);
}
}
function interstitialScroll(pos) {
if( $().velocity ) {
$(settings.target).stop().velocity('scroll', {
duration: settings.scrollSpeed,
easing: settings.easing,
offset: pos,
mobileHA: false
});
} else {
$(settings.target).stop().animate({
scrollTop: pos
}, settings.scrollSpeed,settings.easing);
}
}
function sizePanels() {
var selector = settings.section;
overflow = [];
if(settings.interstitialSection.length) {
selector += "," + settings.interstitialSection;
}
$(selector).each(function(i) {
var $this = $(this);
if(settings.setHeights) {
if($this.is(settings.interstitialSection)) {
overflow[i] = false;
} else {
if(($this.css("height","auto").outerHeight()<$window.height()) || $this.css("overflow")==="hidden") {
$this.css({"height":$window.height()});
overflow[i] = false;
} else {
$this.css({"height":$this.height()});
if(settings.overflowScroll) {
overflow[i] = true;
} else {
overflow[i] = false;
}
}
}
} else {
if(($this.outerHeight()<$window.height()) || (settings.overflowScroll===false)) {
overflow[i] = false;
} else {
overflow[i] = true;
}
}
});
}
function calculatePositions(resize) {
var selector = settings.section;
if(settings.interstitialSection.length) {
selector += "," + settings.interstitialSection;
}
heights = [];
names = [];
elements = [];
$(selector).each(function(i){
var $this = $(this);
if(i>0) {
heights[i] = parseInt($this.offset().top) + settings.offset;
} else {
heights[i] = parseInt($this.offset().top);
}
if(settings.sectionName && $this.data(settings.sectionName)) {
names[i] = "#" + $this.data(settings.sectionName).replace(/ /g,"-");
} else {
if($this.is(settings.interstitialSection)===false) {
names[i] = "#" + (i + 1);
} else {
names[i] = "#";
if(i===$(selector).length-1 && i>1) {
heights[i] = heights[i-1]+parseInt($this.height());
}
}
}
elements[i] = $this;
try {
if($(names[i]).length && window.console) {
console.warn("Scrollify warning: Section names can't match IDs on the page - this will cause the browser to anchor.");
}
} catch (e) {}
if(window.location.hash===names[i]) {
index = i;
hasLocation = true;
}
});
if(true===resize) {
//index, instant, callbacks
animateScroll(index,false,false);
} else {
settings.afterRender();
}
}
function atTop() {
if(!overflow[index]) {
return true;
}
top = $window.scrollTop();
if(top>parseInt(heights[index])) {
return false;
} else {
return true;
}
}
function atBottom() {
if(!overflow[index]) {
return true;
}
top = $window.scrollTop();
if(top<parseInt(heights[index])+(elements[index].outerHeight()-$window.height())-28) {
return false;
} else {
return true;
}
}
}
function move(panel,instant) {
var z = names.length;
for(;z>=0;z--) {
if(typeof panel === 'string') {
if (names[z]===panel) {
index = z;
//index, instant, callbacks
animateScroll(z,instant,true);
}
} else {
if(z===panel) {
index = z;
//index, instant, callbacks
animateScroll(z,instant,true);
}
}
}
}
$.scrollify.move = function(panel) {
if(panel===undefined) {
return false;
}
if(panel.originalEvent) {
panel = $(this).attr("href");
}
move(panel,false);
};
$.scrollify.instantMove = function(panel) {
if(panel===undefined) {
return false;
}
move(panel,true);
};
$.scrollify.next = function() {
if(index<names.length) {
index += 1;
animateScroll(index,false,true);
}
};
$.scrollify.previous = function() {
if(index>0) {
index -= 1;
//index, instant, callbacks
animateScroll(index,false,true);
}
};
$.scrollify.instantNext = function() {
if(index<names.length) {
index += 1;
//index, instant, callbacks
animateScroll(index,true,true);
}
};
$.scrollify.instantPrevious = function() {
if(index>0) {
index -= 1;
//index, instant, callbacks
animateScroll(index,true,true);
}
};
$.scrollify.destroy = function() {
if(!initialised) {
return false;
}
if(settings.setHeights) {
$(settings.section).each(function() {
$(this).css("height","auto");
});
}
$window.off("resize",util.handleResize);
if(settings.scrollbars) {
$window.off('mousedown', manualScroll.handleMousedown);
$window.off('mouseup', manualScroll.handleMouseup);
$window.off('scroll', manualScroll.handleScroll);
}
$window.off(wheelEvent,manualScroll.wheelHandler);
$window.off('keydown', manualScroll.keyHandler);
if (document.addEventListener) {
document.removeEventListener('touchstart', swipeScroll.touchHandler, false);
document.removeEventListener('touchmove', swipeScroll.touchHandler, false);
document.removeEventListener('touchend', swipeScroll.touchHandler, false);
}
heights = [];
names = [];
elements = [];
overflow = [];
};
$.scrollify.update = function() {
if(!initialised) {
return false;
}
util.handleUpdate();
};
$.scrollify.current = function() {
return elements[index];
};
$.scrollify.disable = function() {
disabled = true;
};
$.scrollify.enable = function() {
disabled = false;
if (initialised) {
//instant,callbacks
manualScroll.calculateNearest(false,false);
}
};
$.scrollify.isDisabled = function() {
return disabled;
};
$.scrollify.setOptions = function(updatedOptions) {
if(!initialised) {
return false;
}
if(typeof updatedOptions === "object") {
settings = $.extend(settings, updatedOptions);
util.handleUpdate();
} else if(window.console) {
console.warn("Scrollify warning: Options need to be in an object.");
}
};
}));
I think you are listening wrong event. Use keydown event this will work.
working fiddle

Validate form function jump to error?

I have a form with a validation script that works perfectly. I would however like the form to jump to the fields that doesn't validate or display the name of the fields in the error message.
The code I use to validate is:
else
{
var valid = document.formvalidator.isValid(f);
}
if (flag == 0 || valid == true) {
f.check.value = '<?php echo JUtility::getToken(); ?>';//send token
}
else {
alert('There was an error with the fields..');
return false;
}
return true;
How can I get the alert to name the fields that need to be filled in correctly or jump to the specific field?
Edited ----------
Hi,
Thanks for help so far. I'm very new to JS. The form is in a component of Joomla.
The full function that validates the form is
function validateForm(f){
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer"){
var flag = 0;
for (var i=0;i < f.elements.length; i++) {
el = f.elements[i];
if ($(el).hasClass('required')) {
var idz= $(el).getProperty('id');
if(document.getElementById(idz)){
if (!document.getElementById(idz).value) {
document.formvalidator.handleResponse(false, el);
flag = flag + 1;
}
}
}
}
}
else {
var valid = document.formvalidator.isValid(f);
}
if(flag == 0 || valid == true){
f.check.value='<?php echo JUtility::getToken(); ?>';//send token
}
else {
alert('<?php echo JText::_('JBJOBS_FIEDS_HIGHLIGHTED_RED_COMPULSORY'); ?>');
return false;
}
return true;
}
External js file:
var JFormValidator = new Class(
{
initialize : function() {
this.handlers = Object();
this.custom = Object();
this.setHandler("username", function(b) {
regex = new RegExp("[<|>|\"|'|%|;|(|)|&]", "i");
return !regex.test(b)
});
this.setHandler("password", function(b) {
regex = /^\S[\S ]{2,98}\S$/;
return regex.test(b)
});
this.setHandler('passverify',
function (value) {
return ($('password').value == value);
}
); // added March 2011
this.setHandler("numeric", function(b) {
regex = /^(\d|-)?(\d|,)*\.?\d*$/;
return regex.test(b)
});
this
.setHandler(
"email",
function(b) {
regex = /^[a-zA-Z0-9._-]+(\+[a-zA-Z0-9._-]+)*#([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
return regex.test(b)
});
var a = $$("form.form-validate");
a.each(function(b) {
this.attachToForm(b)
}, this)
},
setHandler : function(b, c, a) {
a = (a == "") ? true : a;
this.handlers[b] = {
enabled : a,
exec : c
}
},
attachToForm : function(a) {
a.getElements("input,textarea,select")
.each(
function(b) {
if (($(b).get("tag") == "input" || $(b)
.get("tag") == "button")
&& $(b).get("type") == "submit") {
if (b.hasClass("validate")) {
b.onclick = function() {
return document.formvalidator
.isValid(this.form)
}
}
} else {
b.addEvent("blur", function() {
return document.formvalidator
.validate(this)
})
}
})
},
validate : function(c) {
c = $(c);
if (c.get("disabled")) {
this.handleResponse(true, c);
return true
}
if (c.hasClass("required")) {
if (c.get("tag") == "fieldset"
&& (c.hasClass("radio") || c.hasClass("checkboxes"))) {
for ( var a = 0;; a++) {
if (document.id(c.get("id") + a)) {
if (document.id(c.get("id") + a).checked) {
break
}
} else {
this.handleResponse(false, c);
return false
}
}
} else {
if (!(c.get("value"))) {
this.handleResponse(false, c);
return false
}
}
}
var b = (c.className && c.className
.search(/validate-([a-zA-Z0-9\_\-]+)/) != -1) ? c.className
.match(/validate-([a-zA-Z0-9\_\-]+)/)[1]
: "";
if (b == "") {
this.handleResponse(true, c);
return true
}
if ((b) && (b != "none") && (this.handlers[b])
&& c.get("value")) {
if (this.handlers[b].exec(c.get("value")) != true) {
this.handleResponse(false, c);
return false
}
}
this.handleResponse(true, c);
return true
},
isValid : function(c) {
var b = true;
var d = c.getElements("fieldset").concat($A(c.elements));
for ( var a = 0; a < d.length; a++) {
if (this.validate(d[a]) == false) {
b = false
}
}
new Hash(this.custom).each(function(e) {
if (e.exec() != true) {
b = false
}
});
return b
},
handleResponse : function(b, a) {
if (!(a.labelref)) {
var c = $$("label");
c.each(function(d) {
if (d.get("for") == a.get("id")) {
a.labelref = d
}
})
}
if (b == false) {
a.addClass("invalid");
a.set("aria-invalid", "true");
if (a.labelref) {
document.id(a.labelref).addClass("invalid");
document.id(a.labelref).set("aria-invalid", "true");
}
} else {
a.removeClass("invalid");
a.set("aria-invalid", "false");
if (a.labelref) {
document.id(a.labelref).removeClass("invalid");
document.id(a.labelref).set("aria-invalid", "false");
}
}
}
});
document.formvalidator = null;
window.addEvent("domready", function() {
document.formvalidator = new JFormValidator()
});
Where would I edit the code as some of you have answered below?
with jquery js library, scroll to element (id selector or class)
<p class="error">There was a problem with this element.</p>
This gets passed to the ScrollTo plugin in the following way.
$.scrollTo($('p.error:1'));
see source
Using jQuery's .each, loop over the fields. On every iteration the item that is being invesitigated will be under the this variable.
Therefore, this.id gives the id of the element you're looking for. Store these to collect all the incorrect fields, then highlight them or print their names in a message.
Keep in mind, this is the basic idea, I cannot give an actual answer until you show the code that handles the form.
Kind regards,
D.
You can have your isValid routine return the error message instead of returning a boolean.
In isValid, you can build up the error message to include the field names with errors.
Instead of checking "valid == true", you will check "errorMessage.length == 0".
If you want to focus on an error field (you can only focus on one), then do that in the isValid routine as well.
function isValid(f) {
var errorMessage = "";
var errorFields = "";
var isFocused = false;
...
if (field has an error) {
errorFields += " " + field.name;
if (!isFocused) {
field.focus();
isFocused = true;
}
}
...
if (errorFields.length > 0) {
errorMessage = "Errors in fields: " + errorFields;
}
return (errorMessage);
}
then, in your calling routine:
var errorMessage = isValid(f);
if (flag == 0 || errorMessage.length == 0) {
f.check.value='<?php echo JUtility::getToken(); ?>';//send token
}
else {
alert(errorMessage);
return false;
}
return true;

Categories

Resources