stop for execution javascript? - javascript

Well, I'm trying to get him to make some fields, if any of them is equal, it's the message and, though my message is giving non-stop, direct, how can I make it stop giving a lot of alert?
function sendAll(){
for (i = 1;i <=10;i ++) {
for (o = 1;o <=10;o ++) {
if(document.getElementById("table" + i).value==document.getElementById("table" + o).value){
alert("Some field is equal, check again.");
break;
return false;
}
}
}
}

You don't need break statement, just remove it. return statement will do the rest
use
function sendAll() {
for (i = 1; i <= 10; i++) {
for (o = 1; o <= 10; o++) {
if (document.getElementById("table" + i).value == document.getElementById("table" + o).value) {
alert("Some field is equal, check again.");
//break;
return false;
}
}
}
//If you are using for validation purpose return true
// as default
return true;
}

Your break simply stops the inner-most loop, but allows the outer loop to continue. To break out of the function entirely, just use a return:
function sendAll(){
for (i = 1;i <=10;i ++) {
for (o = 1;o <=10;o ++) {
if(document.getElementById("table" + i).value==document.getElementById("table" + o).value){
alert("Some field is equal, check again.");
return false;
}
}
}
return true; // suggested by Mike W
}

Try something like this
function sendAll(){
var bEqual = false;
for (i = 1;i <=10;i ++) {
for (o = 1;o <=10;o ++) {
if(document.getElementById("table" + i).value==document.getElementById("table" + o).value){
bEqual = true;
}
}
}
if (bEqual) {
alert("Some field is equal, check again.");
}
return bEqual;
}

Perhaps you could do:
function sendAll(){
if (!fieldsOk()) {
alert('some message');
}
}
function fieldsOk() {
for (i = 1;i <=10;i ++) {
for (o = 1;o <=10;o ++) {
if(document.getElementById("table" + i).value==document.getElementById("table" + o).value){
return false;
}
}
}
return true;
}

Related

How do I get a toggle button to toggle an array back and forth from descending to ascending?

I am using bubbleSort, and I can get the array to toggle from its original order to descending, but I am having trouble getting it to go from descending back to ascending. Should I just copy the bubbleSort code and flip the greater than/less than signs? Any help is appreciated!
var myStuff = [];
function myfunctionA() {
var enteredvalue = document.getElementById("numbers").value;
// alert(typeof Number(document.getElementById('numbers').value));
if (enteredvalue == "") {
alert("Input is not a number");
} else if (isNaN(enteredvalue)) {
alert('You need to enter a valid number!');
}
var elementExists = false;
var x = document.getElementById('numbers').value;
for (var i = 0; i < myStuff.length; i++) {
if (myStuff[i] == Number(x)) {
elementExists = true;
}
}
if(elementExists != true) {
myStuff.push(Number(enteredvalue));
alert('Thank You for entering a valid number.');
} else {
alert('Element is here');
}
}
function myfunctionB() {
window.alert(myStuff.length);
}
function myfunctionC() {
var sum = 0;
for(var i = 0; i < myStuff.length; i++) {
sum+=myStuff[i];
}
alert(sum);
}
function myfunctionD() {
if (myStuff.length == 0) {
alert("already empty");
} else {
myStuff = [];
}
alert("Array Empty");
}
function myfunctionE() {
alert(myStuff.join('\n'));
{
if (myStuff == []) {
alert("Enter something into Array")
}
}
}
function bubbleSort() {
var sorted = true;
var temp;
while(sorted) {
sorted = false;
for(var i = 0; i < myStuff.length-1; i++) {
if(myStuff[i] < myStuff[i+1]) {
temp = myStuff[i];
myStuff[i] = myStuff[i+1];
myStuff[i+1] = temp;
sorted = true;
}
}
}
}
First you'll need a toggle to tell which way you are going.
var isAscending = false;
Then in your bubbleSort function inside the for-statement, above the if-statement.
var sortComparison;
if (isAscending) sortComparison = myStuff[i] > myStuff[i];
if (!isAscending) sortComparison = myStuff[i] < myStuff[i];
Then replace your if-statement with:
if (sortComparison)
Finally, once you have finished sorting, you can toggle your variable:
isAscending = !isAscending;
Though, I'd recommend using a toggled variable and simply using sort() and reverse() instead.
https://jsfiddle.net/ytcax0qc/

How to print the numbers in alert box?

This code is showing the alert box when the two numbers entered are same,now I want show the numbers in the alert box it is showing only one number,but I want to show each number which is same for example,if I enter 83 in two input boxes and 85 in other two input boxes,the alert box should show 83 and 85,you can not enter these numbers more than once.
function validateForm() {
for (var x = 0; x < 81; x++) {
for (var y = x + 1; y < 81; y++) {
if (document.forms["myForm"]['pk' + x].value == document.forms["myForm"]['pk' + y].value) {
if (document.forms["myForm"]['pk' + x].value == "") {
return true;
} else {
alert('You can not enter a number more than once');
return false;
}
}
}
}
return true;
}
A completely different take on it, 81 iterations only, rather than 3000+
function validateForm() {
var q = {}, a = [];
for (var i=0; i<81; i++) {
var value = document.forms["myForm"]['pk'+i].value;
if (value !== "") {
if (q[value]) {
if (q[value] < 2) {
a.push(value);
}
q[value] ++;
}
else {
q[value] = 1;
}
}
}
if(a.length) {
alert(a.join(', ') + ' You can not enter a number more than once');
return false;
}
return true;
}
This loops through all the values a single time, keeping a tally of how many of each value there is (var q) - if a tally of a value hits 2, the value is added to the array (var a). So, triples, quadruples etc, will only be reported once.
If a.length > 0, the alert is shown and false is returned
Do not use return inside the loop, else declare a variable say validate and store true and false values in it and return it at the end, else the function execution will stop at return. Modified code is:
function validateForm() {
var validate = true;
for (var x = 0; x < 81; x++) {
for (var y = x + 1; y < 81; y++) {
if (document.forms["myForm"]['pk' + x].value == document.forms["myForm"]['pk' + y].value) {
if (document.forms["myForm"]['pk' + x].value == "") {
} else {
alert('You can not enter a number more than once. Duplicate number is:'+ document.forms["myForm"]['pk' + x].value);
validate = false;
}
}
}
}
return validate;
}
From your code, this can help you
<script>
function validateForm() {
var val1,val2;
for (var x=0; x<81; x++) {
for (var y=x+1; y<81; y++) {
val1 = document.forms["myForm"]['pk'+x].value;
val2 = document.forms["myForm"]['pk'+y].value
if (document.forms["myForm"]['pk'+x].value==document.forms["myForm"]['pk'+y].value) {
if ( document.forms["myForm"]['pk'+x].value=="") {
return true;
}
else {
alert(val1 + 'and'+ val2 +',You can not enter a number more than once');
return false;
}
}else{
alert(val1 + 'and'+ val2 +',You can not enter a number more than once');
return false;
}
}
}
return true;
}
</script>

Shortening if, else if, else if ... else using loops

I have the following lines of code:
$(function(){
$("div").scroll(function() {
function hpos(id) {
var pos = $("#" + id).position();
return pos.top;
}
function final(id) {
$("#header").html($("#" + id).html()),
$("h1").css("visibility","visible"),
$("#" + id).css("visibility","hidden");
}
if (hpos(5) < 0) {
final(5);
}
else if (hpos(4) < 0) {
final(4);
}
else if (hpos(3) < 0) {
final(3);
}
else if (hpos(2) < 0) {
final(2);
}
else {
final(1);
}
});
});
Shouldn't I be able to shorten it by using a loop instead of the else if statements? I can't find a way to make the loops work with my position().
for (var i = 5; i > 0; i--){
if (hpos(i) < 0) {
final(i);
break;
}
}
would something like this work? Not tested by the way
This should be shorter:
$.each([5,4,3,2], function(i,v) {
if( hpos(v) < 0 ) {
final(v);
return false;
} else if( v === 2 ) {
final(1);
}
});
An easier way to do lots of else if statements is to use the case method.
In case you need a while version:
:)
var elemId = 5;
while (elemId > 1) {
if (hpos(elemId) < 0) {
break;
}
elemId--;
}
final(elemId);

javascript for loop dosn't loop through users created

OK so I am making a register and login for a forum using javascript and localstorage. "School assignment" My problem is that when i created multiple user and store them in the localstorage, my for loop does not loop through them all, only the first one. So i can only access the forum with the first user i create.
function login () {
if (checklogin()) {
boxAlert.style.display = "block";
boxAlert.innerHTML = "Welcome" + "";
wallPanel.style.display = "block";
} else {
boxAlertfail.style.display = "block";
boxAlertfail.innerHTML = "Go away, fail";
}
}
function checklogin (){
for (var i = 0; i < aUsers.length; i++){
if (aUsers[i].email == inputLoginMail.value && aUsers[i].password == inputLoginPassword.value){
return true;
}else{
return false;
}
}
}
how about:
function checklogin() {
var validLogin = false;
for (var i = 0; i < aUsers.length; i++) {
if (aUsers[i].email == inputLoginMail.value
&& aUsers[i].password == inputLoginPassword.value) {
validLogin = true;
break;
}
}
return validLogin;
}
Ouch! You are returning false on very first attempt. The best way is to set a variable and then check for it.
function checklogin() {
var z = 0;
for (var i = 0; i < aUsers.length; i++) {
if (aUsers[i].email == inputLoginMail.value && aUsers[i].password == inputLoginPassword.value) {
z = 1;
break;
} else {
z = 0;
}
if (z == 1) {
// User logged in
} else {
// Fake user
}
}

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