This is my code for checking a register page. It says that variables i and j are already defined, although it's local variables and not global. What could I do in this situation? How can I make the vars locally and not globally? Help is really appreciated, I am a new student in Computer Science.
function checkName() { // בודק על
var n = document.getElementById("FullName").value;
var len = n.length;
var no = "!##$%^&*()-_+=\'|][}{><./,;:?,";
var num = "0123456789";
if (n == "") {
document.getElementById("errName").innerHTML = "רשום את השם בבקשה";
return false;
}
for (var i = 0; i < n.length; i++) {
if (n.charAt(i) == " ") {
len--;
}
}
if (len < 2) {
document.getElementById("errName").innerHTML = "לא הגיוני שם עם אות אחת";
return false;
}
for (var i = 0; i < n.length; i++) {
if (n.charAt(i) >= "a" && n.charAt(i) <= "z") {
document.getElementById("errName").innerHTML = "לא הגיוני שם עם אותיות באנגלית";
return false;
}
}
for (var i = 0; i < no.length; i++) {
for (var j = 0; j < n.length; j++) {
if (no.charAt(i) == n.charAt(j)) {
document.getElementById("errName").innerHTML = "אסור תווים מיוחדים";
return false;
}
}
}
for (var i = 0; i < num.length; i++) {
for (var j = 0; j < n.length; j++) {
if (num.charAt(i) == n.charAt(j)) {
document.getElementById("errName").innerHTML = "אסור מספרים";
return false;
}
}
}
for (var i = 0; i < 3; i++) {
if (n[i] == ' ') {
document.getElementById("errName").innerHTML = "אסור רווחים בהתחלה";
return false;
if (n[i + 1] == ' ') {
document.getElementById("errName").innerHTML = "אסור רווחים בהתחלה";
return false;
}
}
}
document.getElementById("errName").innerHTML = "";
return true;
}
Javascript has function scope, so defining any variable in a function with var will make it exist throughout the function.
In each for loop, you redefine i with var i = 0. For example:
for (var i = 0; i < n.length; i++) {
if (n.charAt(i) == " ") {
len--;
}
}
...
for (var i = 0; i < num.length; i++) {
for (var j = 0; j < n.length; j++) {
if (num.charAt(i) == n.charAt(j)) {
document.getElementById("errName").innerHTML = "אסור מספרים";
return false;
}
}
}
You can add a var i; at the top of the function instead, and simply say i=0 in your loops, so you don't define it multiple times.
Consider looking into using let in newer JS versions.
Try to use new ES6 let instead of var to declare a variables in your functions/project.
This will solve your issue with global name scope.
You can read more here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
You need to look into function scoping. As var has scope of function in which it is defined.
So in your case variable i has access inside checkName function. Using let will help you out in above scenario.
Related
How would I go about calling a function multiple times in different parts of my code. Currently I am just replicating the function and giving all of the variables a different name and calling that separate variable. I will add an example below. The method works but there is no way its efficient. What would be the better way to do it? Thank you for the help and I apologize for the silly question.
JS
// Variable 1
const filterButtons = document.querySelector("#filter-btns").children;
const items = document.querySelector(".blog__content").children;
for(let i =0; i < filterButtons.length; i++) {
filterButtons[i].addEventListener("click", function(){
for (let j =0; j < filterButtons.length; j++) {
filterButtons[j].classList.remove("active2")
}
this.classList.add("active2");
const target = this.getAttribute("data-target")
for (let k = 0; k < items.length; k++) {
items[k].style.display = "none";
if (target == items[k].getAttribute("data-id")) {
items[k].style.display = "block";
}
if (target == "all") {
items[k].style.display = "block";
}
}
})
}
// Variable 2
const filterButtons2 = document.querySelector("#filter-btns2").children;
const items2 = document.querySelector(".blog__content").children;
for(let i =0; i < filterButtons2.length; i++) {
filterButtons2[i].addEventListener("click", function(){
for (let j =0; j < filterButtons2.length; j++) {
filterButtons2[j].classList.remove("active2")
}
this.classList.add("active2");
const target = this.getAttribute("data-target")
for (let k = 0; k < items2.length; k++) {
items2[k].style.display = "none";
if (target == items2[k].getAttribute("data-id")) {
items2[k].style.display = "block";
}
if (target == "all") {
items2[k].style.display = "block";
}
}
})
}
HTML
<div id="filter-btns">
<a data-target="corn">
<span>Corn</span>
</a>
</div>
<div id="filter-btns2">
<a data-target="chicken">
<span>Chicken</span>
</a>
</div>
First, you need a function to call if you want to call it twice
function fn(query) {
const filterButtons = document.querySelector(query).children;
const items = document.querySelector(".blog__content").children;
for (let i = 0; i < filterButtons.length; i++) {
filterButtons[i].addEventListener("click", function () {
for (let j = 0; j < filterButtons.length; j++) {
filterButtons[j].classList.remove("active2");
}
this.classList.add("active2");
const target = this.getAttribute("data-target");
for (let k = 0; k < items.length; k++) {
items[k].style.display = "none";
if (target == items[k].getAttribute("data-id")) {
items[k].style.display = "block";
}
if (target == "all") {
items[k].style.display = "block";
}
}
});
}
}
Then you can call it twice
fn('#filter-btns');
fn('#filter-btns2');
function solution(string, searchValue) {
let answer;
for (let i = 0; i < string.length; i++) {
var count_no_string = 0;
//case 1
if (searchValue[0] == string[i]) {
let save = i;
let count = 0;
for (let j = 0; j < searchValue.length; j++) {
if (searchValue[j] == string[save + j]) {
count = count + 1;
if (searchValue.length == count) {
answer = save;
return answer;
} else{
console.log('f'+ count +' '+ searchValue.length);
}
} else {
console.log('일치하는 문서가 없습니다' );
return -1;
}
}
}
//case2
else if(searchValue[0] != string[i]){
count_no_string = count_no_string+1;
console.log('test ' + count_no_string);
if(count_no_string == string.length){
//retrun -1;
return -1;
}
}
}
}
i don't know why count_no_string variable is always '1'
why?..
i found let, var, const js variable concept, but i can't solve it
thanks you so much
.........
.........
.......
.........
I was going through a reduced row echelon form code for javascript from this website: http://rosettacode.org/wiki/Reduced_row_echelon_form#JavaScript and I was trying to put it into simpler code so that I could understand what each instruction did. I then ran into: while (this.mtx[i][lead] == 0). I understand what the this.mtx[i] is but I don't know what [lead] in the context of being right after mtx[i] does. Your helps is greatly appreciated. Here is the code:
Matrix.prototype.toReducedRowEchelonForm = function() {
var lead = 0;
for (var r = 0; r < this.rows(); r++) {
if (this.columns() <= lead) {
return;
}
var i = r;
while (this.mtx[i][lead] == 0) {
i++;
if (this.rows() == i) {
i = r;
lead++;
if (this.columns() == lead) {
return;
}
}
}
var tmp = this.mtx[i];
this.mtx[i] = this.mtx[r];
this.mtx[r] = tmp;
var val = this.mtx[r][lead];
for (var j = 0; j < this.columns(); j++) {
this.mtx[r][j] /= val;
}
for (var i = 0; i < this.rows(); i++) {
if (i == r) continue;
val = this.mtx[i][lead];
for (var j = 0; j < this.columns(); j++) {
this.mtx[i][j] -= val * this.mtx[r][j];
}
}
lead++;
}
return this;
}
Below is my code which is taking time in the for loop to extract data from one object and filling another object. Is there any way to reduce the time of execution? I have tried a while loop but it is not helping that much. Kindly help
function SetGridWithData(result) {
if (!result) {
return;
}
CtrlBillableItem_SearhedBillableItems = result
var boxOfJson = [];
var j = 100;
if (result.length >= 100) {
if (PagingLastRecNum == 0) {
btnPrevious.style.display = 'none';
for (var i = 0; i < j; i++) {
boxOfJson.push(result[i]);
}
} else {
btnPrevious.style.display = 'inline';
var intializer = (j * PagingLastRecNum) + PagingLastRecNum;
var limiter = intializer + 99;
for (var i = intializer; i < limiter; i++) {
boxOfJson.push(result[i]);
}
}
} else {
btnPrevious.style.display = 'none';
btnNext.style.display = 'none';
for (var i = 0; i < result.length; i++) {
boxOfJson.push(result[i]);
}
}
}
I am trying to implement paging which is done, but 100 data per page first it will check page no 0 if it is then loop one and if other than 0 than else case.
You could try caching result.length at the beginning of your function (following the if check at the beginning)..
function SetGridWithData(result) {
if (!result) { return; }
var resultLength = result.length;
CtrlBillableItem_SearhedBillableItems = result
var boxOfJson = [];
var j = 100;
if (resultLength >= 100) {
if (PagingLastRecNum == 0) {
btnPrevious.style.display = 'none';
for (var i = 0; i < j; i++) {
boxOfJson.push(result[i]);
}
}
else {
btnPrevious.style.display = 'inline';
var intializer = (j * PagingLastRecNum) + PagingLastRecNum;
var limiter = intializer + 99;
for (var i = intializer; i < limiter; i++) {
boxOfJson.push(result[i]);
}
}
}
else {
btnPrevious.style.display = 'none';
btnNext.style.display = 'none';
for (var i = 0; i < resultLength; i++) {
boxOfJson.push(result[i]);
}
}
}
function MoveAddToCartAccordingly()
{
var elems = document.getElementsByClassName('box-collateral box-related');
var av = document.getElementsByClassName('availability in-stock');
var sp = document.getElementsByClassName('product-options');
var ac = document.getElementsByClassName('add-to-cart');
var first = document.getElementsByClassName('item first');
var second = document.getElementsByClassName('item');
for(var k = 0; k < sp.length; k++){
if (getComputedStyle(sp[k]).visibility == "visible")
{
for (var i = 0; i < elems.length; i++) {
if (getComputedStyle(elems[i]).visibility == 'visible') {
for (var j = 0; j < av.length; j++) {
av[j].style.visibility = 'visible';
av[j].id = "someID";
elems[i].appendChild(av[j]);
}
}
else
{
for (var s = 0; s < av.length; s++) {
av[s].style.visibility = 'hidden';
}
for (var l = 0; l < ac.length; l++) {
ac[l].style.marginTop = "-500px";
ac[l].style.marginLeft = "-20px";
}
}
}
}
return;
}
for (var p = 0; p < elems.length; p++) {
if (getComputedStyle(elems[p]).visibility == 'visible') {
for (var q = 0; q < av.length; q++) {
av[q].style.visibility = 'visible';
av[q].id = "someID";
elems[p].appendChild(av[q]);
}
if(elems[p].style.marginTop == "-610px")
{
elems[p].style.marginTop = "-640px";
}
for(var r = 0; r < first.length; r++)
{
if(getComputedStyle(first[r]).visiblity == 'visible'){
for(var m = 0; m < ac.length; m++)
{
if(ac[m].style.marginTop == "-120px")
{
ac[m].style.marginTop ="-140px";
}
}
}
else if(getComputedStyle(first[r]).visiblity == 'visible' && getComputedStyle(second[r]).visiblity == 'visible' )
{
for(var n = 0; n < ac.length; n++)
{
if(ac[n].style.marginTop == "-120px")
{
ac[n].style.marginTop ="-140px";
}
}
}
}
}
}
}
window.onload = MoveAddToCartAccordingly;
can any one whats the wrong with code here actually i am checking if div product option is visible then again i am checking if div with class "box-colatral box-related" if visible if it is not then i am hidding other tag p with class Availability-in-stock and moving add-to- cart div to top position but that one is not working
You have a return statement in your first for loop. I imagine that you are always going to bail on the function call after the first iteration of that loop.