javascript throw statement inside jquery ready? - javascript

So I am wondering if the following is legal, perhaps its not working due to a syntax error.? Simple validation of four rules on a single search field. Thanks for any help towards an elegant and enlightening solution!
$(function() {
$('input.text').focus(function() {
$(this).removeClass('noSubmitX');
$('.enterX').removeClass('now').text( orig);
}); //reset error status
var orig = "Enter the title you want.";
var msg1 = "Title must be between 3 and 63 characters.";
var msg2 = "Title cannot begin or end with a hypen";
var msg3 = "Title cannot contain a hyphen at character positions 3 and 4";
$('form.xSearch').submit(function() {
var theSearch = $('input.text').val();
var xLong = $('input.text').val().length;
var firstx = (theSearch[0]);
var thirdx = (theSearch[2]);
var fourthx = (theSearch[3]);
var lastx = (theSearch[xLong - 1]);
try {
if (xLong < 2 || xLong > 62) {
throw "msg1";
}
else if (firstx == "-") || (lastx == "-") {
throw "msg2";
}
else if (thirdx == "-") && (fourthx == "-")
{
throw "msg3";
}
}
catch (er) {
if (er == 'msg1') {
$('input.text').addClass('noSubmitX');
$('.enterX').addClass('now').text('Title must be between 3 and 63 characters.');
}
if (er == 'msg2') {
$('input.text').addClass('noSubmitX');
$('.enterX').addClass('now').text('Title cannot begin or end with a hypen');
}
if (er == 'msg3') {
$('input.text').addClass('noSubmitX');
$('.enterX').addClass('now').text('Title cannot contain a hyphen at character positions 3 and 4');
}
}
});
});

I think you're running into trouble with your if statements. They need to be wrapped in parenthesis or wrapped like so:
if (xLong < 2 || xLong > 62) {
throw "msg1";
}
else if (firstx == "-" || lastx == "-") {
throw "msg2";
}
else if (thirdx == "-" && fourthx == "-") {
throw "msg3";
}

Related

Using HTML DOM to find element always returns error?

I've been having this issue alot today. Every time I use the HTML DOM for finding parts of the page it always returns an error saying "...is not a function."
Everything from printing to the page to even simply changing the page title just fails.
I've used JSLint, looked it up, etc. and still don't have a clue what this means.
What's even more strange is that I easily got it to work on a different page using the same methods.
Here was an attempt to create a loading animation for the title bar:
var loadingstat;
loadingstat = false;
var pgtA;
pgtA = 0;
setInterval(pgtUpdater(), 80);
function pgtUpdater() {
if (pgtA == 0 && loadingstat = true) {
document.getElementsByTagName[0]("title").innerHTML = "-=-=-";
++pgtA;
} else {
if (pgtA == 1 && loadingstat = true) {
document.getElementsByTagName[0]("title").innerHTML = "=-=-=";
++pgtA;
} else {
if (pgtA == 2 && loadingstat = true) {
document.getElementsByTagName[0]("title").innerHTML = "-/ \-";
++pgtA;
} else {
if (pgtA == 3 && loadingstat = true) {
document.getElementsByTagName[0]("title").innerHTML = "</ \>";
++pgtA;
} else {
if (pgtA == 4 && loadingstat = true) {
document.getElementsByTagName[0]("title").innerHTML = "/ \ ";
++pgtA;
} else {
if (pgtA == 5 && loadingstat = true) {
document.getElementsByTagName[0]("title").innerHTML = "\ /";
++pgtA;
} else {
if (pgtA == 6 && loadingstat = true) {
document.getElementsByTagName[0]("title").innerHTML = "<\ />";
++pgtA;
} else {
if (pgtA == 7 && loadingstat = true) {
document.getElementsByTagName[0]("title").innerHTML = "-\ /-";
++pgtA;
} else {
if (pgtA == 8 && loadingstat = true) {
document.getElementsByTagName[0]("title").innerHTML = "=-=-=";
++pgtA;
} else {
if (pgtA == 9 && loadingstat = true) {
document.getElementsByTagName[0]("title").innerHTML = "-=-=-";
++pgtA;
} else {
if (pgtA == 10 && loadingstat = true || loadingstat = false) {
document.getElementsByTagName[0]("title").innerHTML = "-----";
pgtA = 0;
}
}
}
}
}
}
}
}
}
}
}
}
I've never actually had this issue until today. This always seems to happen whenever I try to edit an element in the page.
Also I am aware that these conditions aren't written properly, I'm currently working on fixing that.
Here's a modified version of your code that you can try at about:blank (run the code from the console):
var title = document.getElementsByTagName('title')[0];
if ( !title ) {
title = document.createElement('title');
document.head.appendChild(title);
}
var frames = ['-=-=-', '=-=-=', '-/ \\-', '</ \\>', '/ \\', '\\ /', '<\\ />', '-\\ /-', '=-=-=', '-=-=-', '-----'];
var i = 0;
setInterval(function() {
title.innerHTML = frames[i];
if ( i++ == 10 ) i = 0;
}, 500);
You are invoking pgtUpdater() in setInterval. Try just passing the function name. I tried an example function in the console, and as u can see the function is only invoked once when parantheses are used, this could be the issue.

Wrong value while getting last symbol in string in Javascript

I have a variable someText where number is stored. Depending on last number I need to add different text. So I convert someText into stiring, get string length in someTextLng and substract for the last symbol someTextLng.
document.write(lastChar + "<br/>"); in my example returns 7 - all ok.
Continuing with if and getting surprise - lastChar = 1. But why? Where is my mistake?
<script type="text/javascript">
var someText = 312347;
someText= someText.toString();
someTextLng = someText.length-1;
var lastChar = someText.substr(someTextLng, 1);
document.write(lastChar + "<br/>");
if (lastChar = "1") {
document.write(lastChar+" Day")
}
else if (lastChar = "2") {
document.write(lastChar+" DayZ")
}
else {
alert ("Wuza");
}
</script>
Why not use the reminder operator % for the last digit?
var last = number % 10;
and later
if (last === 1) {
// do something
}
You need to use == to match the value of lastChar. To get the lastChar you can use reminder operator:
var lastChar = someText % 10;
if (lastChar == 1) {
document.write(lastChar+" Day")
}
else if (lastChar == 2) {
document.write(lastChar+" DayZ")
}
else {
alert ("Wuza");
}
If you want to check for something that equal to something else it's === not =
Your code should be like that
if (lastChar === "1") {
document.write(lastChar+" Day")
}
else if (lastChar === "2") {
document.write(lastChar+" DayZ")
}
else {
alert ("Wuza");
}
:)
var someText = 312347;
someText= someText.toString();
someTextLng = someText.length-1;
var lastChar = someText.substr(someTextLng, 1);
console.log(lastChar + "<br/>");
if (lastChar == "1") {
console.log(lastChar+" Day")
}
else if (lastChar == "2") {
console.log(lastChar+" DayZ")
}
else {
alert ("Wuza");
}
Try this
<script type="text/javascript">
var lastChar = (312347 % 10).toString;
document.write(lastChar + "<br/>");
if (lastChar === "1") {
document.write(lastChar+" Day")
} else if (lastChar === "2") {
document.write(lastChar+" DayZ")
} else {
alert ("Wuza");
}
</script>

NaN error equation

In this javascript code I try to solve a quadratic equation, I've been working on it for an hour and this should tell me the value of a, b and c where y is a(x^2). I'm a relative javascript beginner and would love some help. Why are the values of a, b and c not numbers? The variable names are in italian, in english and in something else(Not even I know what), but I commented what they are. That's one of my bad traits as a student that usually works alone, sorry if it's not easy to understand.
<script type="text/javascript">
var equa=prompt("Scrivi l'equazione senza spazi usando x come incognita e y come x^2");
var a = 0.0; b = 0.0; c = 0.0;//ax2+bx+c
var prima = true; //before or after equal?
var ope = 1;//1add 2sub 3mul 4div
var lasto = 0.0;//last number, used for div and mul
var lastos = 3; //1a2b3c
var errore=0;//is something messed up?
for(var i = 0; i < equa.length;i=i){
if(equa.charAt(i)=='='){
prima = false;
i++;
}else if(equa.charAt(i)=='+'){
ope=1;
i++;
}else if(equa.charAt(i)=='-'){
ope=2;
i++;
}else if(equa.charAt(i)=='*'){
ope=3;
i++;
}else if(equa.charAt(i)=='/'){
ope=4;
i++;
}else{
var nume = "";//Current number in string form
while(i<equa.length && equa.charAt(i)>'0' && equa.charAt(i)<'9'){
nume+=equa.charAt(i);
i++;
}
var lasnum = 0.0;//current number in float form
var lasval = 3; //1a2b3c
if(equa.charAt(i) == 'x'){
lasnum=parseFloat(nume);
lasval = 2;
}else if(equa.charAt(i) == 'y'){
lasnum=parseFloat(nume);
lasval = 1;
}else{
lasnum = parseFloat(nume);
lasval=3;
}
i++;
if( (ope == 1 || ope == 2) && !(equa.charAt(i) =='*' || equa.charAt(i) == '/')){
if(lasval == 1){
if(prima) a+=lasnum;
else a-=lasnum;
}
else if(lasval == 2){
if(prima) b+=lasnum;
else b-=lasnum;
}
else {
if(prima) c+=lasnum;
else c-=lasnum;
}
}else if( (ope==1 || ope == 2) && (equa.charAt(i) =='*' || equa.charAt(i) == '/')){
//zitto e fermo
lasto=lasnum;
lastos=lasval;
}else if( (ope==3||ope == 4)){
if(ope==3){
if(lastos==3){
lasnum*=lasto;
}
if(lastos == 2){
if(lastval==3){
lasnum*=lasto;
lastval=2;
}
if(lastval==2){
lasnum*=lasto;
lastval=1;
}
if(lastval==1){
errore=1;
}
}
if(lastos == 1){
if(lastval == 3){
lasnum*=lasto;
lastval=1;
}else{
errore=1;
}
}
}
if(ope == 4){
if(lastos == 1){
if(lastval==3){
lasnum/=lasto;
lastval=1;
}
if(lastval==2){
lasnum/=lasto;
lastval=2;
}
if(lastval==1){
lasnum/=lasto;
lastval=3;
}
}
if(lastos == 2){
if(lastval==1){
errore=1;
}
if(lastval==2){
lasnum/=lasto;
lastval=3;
}
if(lastval==3){
lasnum/=lasto;
lastval=2;
}
}
if(lastos == 3){
if(lastval==3){
lasnum/=lasto;
}else{
errore=1;
}
}
}
if(equa.charAt(i) =='*' || equa.charAt(i) == '/'){
lasto=lasnum;
lasto=lasval;
}else{
if(lasval == 1){
if(prima) a+=lasnum;
else a-=lasnum;
}
else if(lasval == 2){
if(prima) b+=lasnum;
else b-=lasnum;
}
else {
if(prima) c+=lasnum;
else c-=lasnum;
}
lasto=0;
lastos=3;
}
}
}
}
if(errore==0){
alert("a ="+a+" b="+b+" c="+c);
}else{
alert("AOOOOOOo");
}
</script>
Since the expected input should be in the format "15y+3x+5=20" for example, then this is a simple regular expression:
var equa = prompt("Scrivi l'equazione senza spazi usando x come incognita e y come x^2");
var regex = /^([0-9.]+)y\+([0-9.]+)x\+([0-9.]+)=([0-9.]+)$/;
var matches = regex.exec(equa);
if (matches) {
var a = parseFloat(matches[1]);
var b = parseFloat(matches[2]);
var c = parseFloat(matches[3]) - parseFloat(matches[4]);
var discriminant = b*b - 4*a*c;
if (discriminant < 0) {
alert('No real solutions');
}
else {
var root = Math.sqrt(discriminant);
alert('Root: ' + ((-b + root)/(2*a)) + ', ' + ((-b - root)/(2*a)));
}
}
else {
alert("AOOOOOOo");
}

Javascript: Mathfloor still generating a 0

In my script to generate a playing card, it's generating a 0, even though my random generator is adding a 1, so it should never be 0. What am I doing wrong?! If you refresh, you'll eventually get a "0 of Hearts/Clubs/Diamonds/Spades":
var theSuit;
var theFace;
var theValue;
var theCard;
// deal a card
function generateCard() {
var randomCard = Math.floor(Math.random()*52+1)+1;
return randomCard;
};
function calculateSuit(card) {
if (card <= 13) {
theSuit = "Hearts";
} else if ((card > 13) && (card <= 26)) {
theSuit = "Clubs";
} else if ((card > 26) && (card <= 39)) {
theSuit = "Diamonds";
} else {
theSuit = "Spades";
};
return theSuit;
};
function calculateFaceAndValue(card) {
if (card%13 === 1) {
theFace = "Ace";
theValue = 11;
} else if (card%13 === 13) {
theFace = "King";
theValue = 10;
} else if (card%13 === 12) {
theFace = "Queen";
theValue = 10;
} else if (card%13 === 11) {
theFace = "Jack";
theValue = 10;
} else {
theFace = card%13;
theValue = card%13;
};
return theFace;
return theValue
};
function getCard() {
var randomCard = generateCard();
var theCard = calculateFaceAndValue(randomCard);
var theSuit = calculateSuit(randomCard);
return theCard + " of " + theSuit + " (this card's value is " + theValue + ")";
};
// begin play
var myCard = getCard();
document.write(myCard);`
This line is problematic:
} else if (card%13 === 13) {
Think about it: how a remainder of division to 13 might be equal to 13? ) It may be equal to zero (and that's what happens when you get '0 of... '), but will never be greater than 12 - by the very defition of remainder operation. )
Btw, +1 in generateCard() is not necessary: the 0..51 still give you the same range of cards as 1..52, I suppose.
card%13 === 13
This will evaluate to 0 if card is 13. a % n will never be n. I think you meant:
card % 13 === 0
return theFace;
return theValue
return exits the function; you'll never get to the second statement.

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