Cookie seems not to work - javascript

Since i needed to have some variables of my programs available in all the pages, i decided to use cookies (js-cookie).
if ((Cookies.get('j') == null) || (Cookies.get('j') == 0)) {
Cookies.set('j', 0);
var j = parseInt(Cookies.get('j'));
}
Cookies.set('imuno');
var imuno = Cookies.get('imuno');
Cookies.set('imdue');
var imdue = Cookies.get('imdue');
Then i wrote two functions:
function check1(){
if ((src1 == "") || (src1 == "undefined")) {
alert("Selezionare un'immagine.");
}
else {
controllo();
}
}
and
function check2(){
if ((src2 == "") || (src2 == "undefined")) {
alert("Selezionare un'immagine.");
}
else {
controllo();
}
}
As you can see, they're two check functions that retrieve another function (controllo()) which works like that:
function controllo() {
if (j == 0) {
alert(j);
imuno = src1;
Cookies.set('imuno', src1);
alert(imuno);
location.href = "schienale.html";
j++;
Cookies.set('j', 1);
}
else if (j == 1){
alert(j);
imdue = src2;
Cookies.set('imdue', src2);
alert(imuno,imdue);
location.href = "riep.html";
j++;
Cookies.set('j', 2);
}}
All this code is written in my external .JS file. Now the funcion check1() works perfectly, but when the check2() start running the program doesn't work anymore, as if the cookie j doesn't mantain its value. How can i solve? Thanks all!

Related

How can I avoid heap out of memory?

I wrote this code to get ended my homework as a practice.
This code controls browser with nightmare.js.It just iterates clicking button and waiting for a sec.
But this code issued an error of heap out of memory. I just tried out "--max-old-space-size=4096". but it didn't work...
ANYONE HELP ME??
I checked other than iterations can work. Then putting iterations..., it cannot work due to heap out of memory.
To be honest, I am not good at coding and English. If there are any miswriting, ask me please!
const Nightmare = require('nightmare');
const nightmare = Nightmare({show: true});
const LinguaURL = "";
const NumberOfMine = "";
const PwdOfMine = "";
var i,j = -1;
var selection, progress;
var radioSelect = -1;
function main() {
nightmare
.goto(LinguaURL)
.wait(1000)
.type("input[type='text']", NumberOfMine)
.type("input[type='password']", PwdOfMine)
.click("input[type='submit']")
.wait(5000)
.click('a[href="javascript:document.Study.submit()"]')
.wait(3000)
.click("input[type='button']")
.wait(3000);
for(i = 3;i<43;i++){
nightmare
.click('a[onclick="unit_view_page(\''+i.toString()+'\');"]');
while(true){
j++;
if(j % 4 == 0){
nightmare
.click('input[onclick="select_unit(\'drill\', \''+(1833+j).toString()+'\', \'\');"]')
.wait(1000);
while(true){
radioSelect++;
nightmare
.click('input[id="answer_0_' + radioSelect.toString() +'"]')
.wait(1000)
.click('input[id="ans_submit"]')
.wait(1000)
.evaluate(function (){
return selection = document.querySelector('.btn btn-answer-view form-font-size');
})
.evaluate(function (){
return progress = document.querySelector('btn btn-next-problem form-font-size');
});
if(selection == null && progress == null)break;
if(selection != null){
continue;
}else{
nightmare
.click('input[class="btn btn-next-problem form-font-size"]');
continue;
}
}
if((j + 1) % 10 == 0)break;
}
}
}
nightmare
.wait(100)
.end()
.then(console.log);
}
main();
If I'm not mistaken, I think this is the reason.
function main() {
for(i = 3;i<43;i++){
while(true){
j++;
if(j % 4 == 0){
while(true){
/**** break for the second while. ****/
if(selection == null && progress == null) break;
if(selection != null){
continue;
}else{
continue;
}
}
/**** break for the first while. ****/
// But this code will be run if 'j % 4 == 0',
// and I can't see any assigned the value to 'j' variable inside of 'if'.
// There's no way the result will be true.
if((j + 1) % 10 == 0) { break; }
}
}
}
}
var j = -1;
var limit = 2000 * 4;
while(true){
j++;
if(j != 0 && j % 1000 == 0) console.log("loop: " + j);
// here we go.
if(j % 4 == 0){
while(true){
break;
}
// But this code will be run if 'j % 4 == 0',
// and I can't see any assigned the value to 'j' variable inside of 'if'.
// There's no way the result will be true.
if((j + 1) % 10 == 0) { console.log("your if statement"); break; }
// limit
if (j == limit) { console.log("break using limit"); break; }
}
// Maybe (do you just want to run ten times?)
// if((j + 1) % 10 == 0) { console.log("[maybe] your if statement"); break; }
}
console.log("process end");

JS in page head section isn't excecuting

I have a script that handles a semi-complex contact form. The site is built using a website building platform called Duda and I think there may be timing issues as they load a bunch of scripts of their own. Anyway I'm getting a ReferenceError: price is not defined, error.
Price gets called onChange on inputs, for example:
<input value="Yes" name="dmform-9" type="radio" id="watch-me-hide" checked="checked" onchange="price()"/>
The script works sometimes, then other times not. Very frustrating. Does anyone know how to make sure that my functions get loaded in this situation?
Here is the whole script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var counter = 0;
$(document).ready(function() {
$("input[type="radio"]").click(function() {
alert("here");
var ids = ["#occupiedBy", "#nameOccupied", "#phoneOccupied", "#mobileOccupied", "#emailOccupied"];
if($(this).attr("id") == "watch-me-hide" || $(this).attr("id") == "watch-me-show") {
if ($(this).attr("id") == "watch-me-hide") {
$("#show-me").hide();
ids.forEach((id) => $(id).prop("required", false));
}
else if ($(this).attr("id") == "watch-me-show"){
$("#show-me").show();
ids.forEach((id) => $(id).prop("required", true));
}
else {
}
} else if($(this).attr("id") == "hideShowInDepth-hide" || $(this).attr("id") == "hideShowInDepth-show") {
if ($(this).attr("id") == "hideShowInDepth-hide") {
$("#moreRooms").hide();
price(null);
ids.forEach((id) => $(id).prop("required", false));
}
else if ($(this).attr("id") == "hideShowInDepth-show"){
$("#moreRooms").show();
price(null);
ids.forEach((id) => $(id).prop("required", true));
}
}
else{
}
});
};
function price() {
var priceIncrement = 70;
var minimumPrice = "189.00";
var basic = document.getElementById("hideShowInDepth-hide");
var advanced = document.getElementById("hideShowInDepth-show");
var ids = ["numberAdditionalRooms", "numberLaundries", "bedrooms", "numberLounges", "numberDining", "numberKitchens", "numberBathrooms", "numberHallways", "numberGarages"];
if ((basic.checked == true) && (advanced.checked == false)) {
/* Get number of rooms for basic inspection */
var e = document.getElementById("bedrooms");
var numberOfBedrooms = e.options[e.selectedIndex].value;
if (numberOfBedrooms == 0){
document.getElementById("totalPrice").textContent = "0.00";
}
else if ((numberOfBedrooms <= 3) && (numberOfBedrooms >= 1)){
document.getElementById("totalPrice").textContent = minimumPrice;
}
else if ((numberOfBedrooms <= 6) && (numberOfBedrooms >= 3)){
document.getElementById("totalPrice").textContent = "259.00";
}
else if (numberOfBedrooms > 6){
document.getElementById("totalPrice").textContent = "329.00";
}
else {
alert("Script error: Undefined number of bedrooms")
}
return false;
}
else if ((basic.checked == false) && (advanced.checked == true)) {
/* Get number of rooms for advanced inspection */
ids.forEach(logArrayElements);
if (counter == 0){
document.getElementById("totalPrice").textContent = "0.00";
}
else if (counter == 1){
document.getElementById("totalPrice").textContent = minimumPrice.toFixed(2);
;
}
else {
var money = ((counter * priceIncrement) + +minimumPrice) - +priceIncrement;
document.getElementById("totalPrice").textContent = money.toFixed(2);
}
counter=0;
return false;
}
else if ((basic.checked == false) && (advanced.checked == false)) {
alert("Script error: Neither checkbox is checked");
return false;
}
else if ((basic.checked == true) && (advanced.checked == true)) {
alert("Script error: Both checkboxes are checked");
return false;
}
else{
alert("Script error: Unknown error");
return false;
}
}
function logArrayElements(element, index, array) {
// alert("a[" + index + "] = " + element + " - " + value);
var e = document.getElementById(element);
var strUser = e.options[e.selectedIndex].value;
counter = +counter + +strUser;
}
</script>
watch-me-hide and watch-me-show are radio buttons that when changed they hide or show another section of the contact form to fill out, and make the inputs required or not.
hideShowInDepth-hide and hideShowInDepth-show are the same, but for another div section.
the price function updates the text in a span to reflect a new price when an input value has changed.
price() gets called onchange of dropdowns and radio buttons.
Any help appreciated.

Infinite loop found on line 0

I am trying to make a tic-tac-toe game, but in Codepen my Javascript gives me an error saying "Infinite loop found on line 0. The line number is approximated so look carefully." Here is the pen
See the Pen Tic-Tac-Toe by Maris (#spacegeek224) on CodePen.
and here is my JS:
(function() {
var PLAYERS = ['X','O'];
var TURN = PLAYERS[0];
var BOARD = [new Array(3),new Array(3),new Array(3)];
function togglePlayer() {
TURN = (TURN == PLAYERS[0]) ? PLAYERS[1] : PLAYERS[0];
}
$('.square').click(function(e) {
if ($(e.target).attr('data-p')) {
} else {
$(e.target).attr('data-p',TURN).text(TURN);
BOARD[$(e.target).attr('data-y')][$(e.target).attr('data-x')] = TURN;
if (checkWin(BOARD)) {
$('.turn').attr('data-p',checkWin(BOARD)).text(checkWin(BOARD) + " wins!");
$('.square:not([data-p])').attr('data-p',true);
}
else {
togglePlayer();
$('.turn').attr('data-p',TURN).text(TURN+"\'s turn");
}
}
});
function checkWin(board) {
for (var i = 0;i<3;i++) {
if (board [0][i] !== undefined)
if (board[0][i]==board[1][i] && board[1][i] == board[2][i])
return board[0][i];
else if (board [i][0] !== undefined)
if (board[i][0]==board[i][1] && board[i][1] == board[i][2])
return board[i][0];
else if (board[1][1] !== undefined)
if (board[0][0] == board[1][1] && board[1][1] == board[2][2])
return board[1][1];
else if (board[0][2] == board[1][1] && board[1][1] == board[2][0])
return board[1][1];
}
return false;
}
$('.container').on('dblclick',function() {
$('.square').removeAttr('data-p').text('');
BOARD = [new Array(3),new Array(3),new Array(3)];
TURN = PLAYERS[0];
$('.turn').attr('data-p',TURN).text(TURN+"\'s turn");
});
})();
I figured it out, and i cant believe I didn't see this before. In the checkWin function I should have put if instead of if else inside the for loop.

Checkboxes and trying to save the state of all checkboxes for the user when they return

function getFormState() {
var fields = document.getElementsByTagName('form')[0].elements;
if (fields.length === 0) {
return;
};
for (var i = 0; i <= fields.length - 1; i++) {
var name = fields[i].getAttribute('name');
if (document.getElementByTagName('name').checked === true) {
localStorage.setItem('name', "true");
} else {
localStorage.setItem('name', "false");
}
}
}
function fillFormState() {
var fields = document.getElementsByTagName('form')[0].elements;
if (fields.length === 0) {
return;
};
for (var i = 0; i <= fields.length - 1; i++) {
var name = fields[i].getAttribute('name');
getStatus = localStorage.getItem('name'); {
if (getStatus === "true") {
console.log("its checked");
document.getElementByTagName("name").setAttribute('checked', 'checked');
} else {
console.log("its not checked");
}
}
}
} // run the below functions when the web page is loadedwindow.onload = function () {
// check if HTML5 localStorage is supported by the browser
if ('localStorage' in window && window['localStorage'] !== null) {
// get the form state
getFormState();
// save the state of the form each X seconds (customizable)
setInterval('fillFormState()', 1 * 1000);
}
};
But it doesn't seem to work. And Im trying to figure out why. Im not very experienced with javascript so it might be quite obvious. Sorry for that. Im trying.
I'm guessing your localStorage is never being set because of this loop:
for (var i = 0; i <= fields.length - 1; i++) {
var name = fields[i].getAttribute('name');
if (document.getElementByTagName('name').checked === true) {
localStorage.setItem('name', "true");
} else {
localStorage.setItem('name', "false");
}
}
There is no document.getElementByTagName, and you are also searching for "name" instead of your variable name.
for (var i = 0; i <= fields.length - 1; i++) {
var name = fields[i].getAttribute('name');
if (fields[i].checked === true) { //Check the current field
localStorage.setItem(name, "true"); //Set the actual name, not "name"
} else {
localStorage.setItem(name, "false");
}
}

Javascript Phone number validation Paratheses sign

I did some searching and there where others asking this question and answers to it but none that seemed to fit what I was trying to do. Basically I'm working on a validation of the phone entry that accepts (123)4567890 as an entry. I've already implemented one that accepts a simple number string such as 1234567890 and one with dashes 123-456-7890. I know I'm making a simple mistake somewehre but I can't figure out what I'm doing wrong.
Here's the phone number with dashes form that is working:
//Validates phone number with dashes.
function isTwelveAndDashes(phone) {
if (phone.length != 12) return false;
var pass = true;
for (var i = 0; i < phone.length; i++) {
var c = phone.charAt(i);
if (i == 3 || i == 7) {
if (c != '-') {
pass = false;
}
}
else {
if (!isDigit(c)) {
pass = false;
}
}
}
return pass;
}​
and this is the one I can't manage to work out.
function isTwelveAndPara(phone) {
if (phone.length != 12) return false;
var pass = true;
for (var i = 0; i < phone.length; i++) {
var c = phone.charAt(i);
if (i == 0) {
if (c != '(') {
pass = false;
}
}
if (i == 4) {
if (c != ')') {
pass = false;
}
}
else {
if (!isDigit(c)) {
pass = false;
}
}
}
return pass;
}​
You can do it very easily with regex:
return !!phone.match(/\(\d{3}\)\d{7}/g)
Live DEMO
Update:
The code you had didn't work because you forgot the else if:
else if (i == 4) { // Added the "else" on the left.
Checking phone number with RegEx is certainly the way to go. Here is the validation
function that ignores spaces, parentheses and dashes:
check_phone(num) {
return num.replace(/[\s\-\(\)]/g,'').match(/^\+?\d{6,10}$/) != null}
You can vary the number of digits to accept with the range in the second regular expression {6,10}. Leading + is allowed.
Something like that (a RegExp rule) can make sure it matches either rule.
var numbers = ['(1234567890','(123)4567890','123-456-7890','1234567890','12345678901'];
var rule = /^(\(\d{3}\)\d{7}|\d{3}-\d{3}-\d{4}|\d{10})$/;
for (var i = 0; i < numbers.length; i++) {
var passed = rule.test(numbers[i].replace(/\s/g,''));
console.log(numbers[i] + '\t-->\t' + (passed ? 'passed' : 'failed'));
}
EDIT:
function isDigit(num) {
return !isNaN(parseInt(num))
}
function isTwelveAndPara(phone) {
if (phone.length != 12) return false;
for (var i = 0; i < phone.length; i++) {
var c = phone.charAt(i);
if (i == 0) {
if (c != '(') return false;
} else if (i == 4) {
if (c != ')') return false;
} else if (!isDigit(c)) return false;
}
return true;
}
// or...
function isTwelveAndPara(phone) {
if (phone.length != 12 || phone.charAt(0) != '(' || phone.charAt(4) != ')') return false;
for (var i = 1; i < phone.length, i != 4; i++) {
if (!isDigit(phone.charAt(i))) return false;
}
return true;
}

Categories

Resources