Trouble with basic javascript - javascript

I'm trying to do some extremely simple form validation, my current problem is that my window.onload function doesn't call in the function I specify.
When I watch the flow of logic with firebug it just skips to the end of the code.
Here is an example of my code:
window.onload = init;
function init() {
var regForm = document.getElementById("registerform");
regForm.onsubmit = validatepostcode();
}
function validatepostcode() {
var postCode = document.getElementById("postcode");
var postCodeStr = postCode.charAt(0);
var state = document.getElementById("state");
var result = true;
if (postCodeStr == 3 || 8 && state == "Vic") {
result = true;
} else if (postCodeStr == (1 || 2) && state == "NSW") {
result = true;
} else if (postCodeStr == (4 || 9) && state == "QLD") {
result = true;
} else if (postCodeStr == 0 && state == "NT" || state == "ACT") {
result = true;
} else if (postCodeStr == 6 && state == "WA") {
result = true;
} else if (postCodeStr == 5 && state == "SA") {
result = true;
} else if (postCodeStr == 7 && state == "TAS") {
result = true;
} else
result = false;
if (result = false) {
alert("Your postcode does not match your state")
}
}

Five problems:
In init, you have this:
regForm.onsubmit = validatepostcode();
That calls validatepostcode and puts its return value in onsubmit. You probably meant to put the function itself it, not its return value in. Remove the parentheses:
regForm.onsubmit = validatepostcode;
In validatepostcode, you're fetching elements like this:
var postCode = document.getElementById("postcode");
…but then try to use them as values, like this:
var postCodeStr = postCode.charAt(0);
But an element and the current value of that element are not the same thing. More likely, you meant to retrieve the value on the first line:
var postCode = document.getElementById("postcode").value;
Same goes for state.
In validatepostcode, you have lines like this:
} else if (postCodeStr == (1 || 2) && state == "NSW") {
Specifically, 1 || 2 won't work like that. It will look at them like booleans and say, “one or two? well, they're both truthy…true it is!” and you'll essentially be doing
} else if (postCodeStr == true && state == "NSW") {
(Actually, it uses 1, not true, since the first operand was truthy, but that's not the important point here.)
Instead of using that abbreviated notation, you'll have to write it out longhand:
} else if ((postCodeStr == 1 || postCodeStr == 2) && state == "NSW") {
You mixed up = and == here:
if(result=false){
= will set result to false and leave the condition always false. Change it to == to test equality:
if(result==false){
You probably meant to return result at the end to prevent the form from being submitted when there is a validation error. With the other changes applied, you'd get an alert if there was a validation error, but it'd go on submitting anyway. As such, add a return result at the end of the validatepostcode function.

Related

Changing javascript eval method to another solution

I try to get rid of an ugly javscript eval method (Cause we all know it is unsecure).
I have the following problem. I build a dynamic searchstring.
Depends on the TLD a user decided to search for.
Here is my code:
if (tld == 0) {
var searchString = 'value.tld != ""';
}
if (tld == 1) {
var searchString = 'value.tld == "de"';
}
if (tld == 2) {
var searchString = 'value.tld == "com" || value.tld == "net" || value.tld == "org" || value.tld == "info" || value.tld == "biz"';
}
if (tld == 3) {
var searchString = 'value.tld == "io"';
}
Depending on the search parameter 'searchstring', I build this routine with eval:
if (eval(searchString)) {
// Do something special, depends on the tld variable
}
How can i rebuild this without using 'eval'. The premission is, that the first part of the code is beeing untouched.
Thanks in advance
Nick
How about:
let choices = {
1: ['de'],
2: ['com', 'net', 'org', 'info', 'biz'],
3: ['io']
};
function check(tldparam) {
if (tld === 0) {
return value.tld !== "";
} else {
return tld === tldparam && choices[tldparam].includes(value.tld);
}
}
And we test it like:
// Got this value from somewhere
let tld = 2;
let value = {tld: 'net'};
// This is my checking criterion
let tldparam = 2;
if (check(tldparam)) {
// Do something special, depends on the tld variable
}
Does it serve your purpose?

How to make usernames banned on a website

How can I find out if a text input is a certain text?
I tried this
<script>
var b = document.getElementById('button')
var u = document.getElementById('username')
var p = document.getElementById('password')
var bannedUsers = ["user1012"];
b.onclick = function() {
if(u.value.length <= 20 && p.value.length >= 6 && u.value.length >= 3 && !u.value === bannedUsers) {
location.href = "";
};
if(u.value.length > 20) {
return alert('Username needs to be below 20 characters.')
} else if(u.value.length < 3) {
return alert('Username needs to be above 2 characters')
}
if(p.value.length < 6) {
return alert('Password needs to be over 6 characters.')
}
if(u.value === bannedUsers) {
return alert('That username is banned.')
}
}
</script>
But it ended up just taking me to the page instead of saying "This username is banned"
You need to use the includes method.
bannedUsers.includes(u.value)
what you're doing right now is checking if the string is the array bannedUsers, translating to this: 'user1012' === '[object Object]'
You can use the Array.prototype.includes method to test if a given value is in an array. includes will return a boolean true or false.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
if (bannedUsers.includes(u.value) {
return alert('That username is banned.')
}

checking two values on 'enter' press

I want to check the value of a input field against a value in my js object on pressing enter. the if (document.getElementById("barcode").value === element.anr) works. however, i only want it to execute document.getElementById("next").click(); if barcodecounter is equal to element.menge.
Basically if element.menge has a value of 5, the first time document.getElementById("barcode").value is equal to element.anr I want barcodecounter to increase by 1 and when its equal to element.menge it should execute document.getElementById("next").click();.
Currently if e.g. element.menge is 5, it still executes document.getElementById("next").click(); even when I only provided it once instead of 5 times.
What am I doing wrong?
document.getElementById("barcode").addEventListener("keypress", function(e) {
let barcodecounter;
if (event.which == 13 || event.keyCode == 13) {
if (document.getElementById("barcode").value === element.anr) {
barcodecounter++;
if (barcodecounter = element.menge) {
document.getElementById("next").click();
}
console.log(document.getElementById("barcode").value, element.anr);
console.log(element.menge);
}
else if (document.getElementById("barcode").value != element.anr){
alert("Falscher Artikel");
}
}
});
You are using an assignment = not a boolean compare ==, simple change. I also added some adjustments to the code to initialize stuff. element might be something else but was not in there
// used this but not declared:
//let element = {};
//element.anr = 0;
//element.menge = 0;
//OR use, I assume numerics heres
let element = {
anr: 0,
menge: 0
};
document.getElementById("barcode").addEventListener("keypress", function(e) {
let barcodecounter = 0;// set initial value;
if (event.which == 13 || event.keyCode == 13) {
if (document.getElementById("barcode").value === element.anr) {
barcodecounter++;
if (barcodecounter == element.menge) {
document.getElementById("next").click();
}
console.log(document.getElementById("barcode").value, element.anr);
console.log(element.menge);
} else /* no need for else if here */ {
alert("Falscher Artikel");
}
}
});

How to use javascript validating two text areas

The below works, how would i go about including a 2nd "txtArea2"? I've tried joining a & (document.getElementById("txtArea2").value == '') but doesnt work. I'm new to js syntax if someone could help.
if(document.getElementById("txtArea1").value == '')
{
alert("debug");
document.getElementById("txtArea1").style.display ="none";
return false;
};
I'm not sure if I understand your question correctly but you probably want to compare them with || (OR) operator, so if txtArea1 or txtArea2 is empty then the validation shall not pass. That means both textareas will be required fields.
if (document.getElementById("txtArea1").value == '' || document.getElementById("txtArea2").value == '')
{
alert("debug");
document.getElementById("txtArea1").style.display ="none";
return false;
};
Double && specifies the AND condition.
if (document.getElementById("txtArea1").value == '' && document.getElementById("txtArea2").value == '')
If you want to treat both separately, you'll have to use two separate if statements as well. (I outsourced the textareas into variables for readability)
var txtarea1 = document.getElementById("txtArea1");
var txtarea2 = document.getElementById("txtArea2");
if(txtarea1.value == '')
{
alert("debug");
txtarea1.style.display = "none";
return false;
};
if(txtarea2.value == '')
{
alert("debug");
txtarea2.style.display = "none";
return false;
};
If you want to do one thing if either of them (1 or 2) is empty, try this:
if(txtarea1.value == '' || txtarea2.value == '')
{
alert("debug");
txtarea1.style.display ="none";
txtarea2.style.display ="none";
return false;
};
var t1 = document.getElementById("txtArea1").value;
var t2 = document.getElementById("txtArea2").value;
if( t1 == '' || t2 == '')
{
alert("debug");
document.getElementById("txtArea1").style.display ="none";
return false;
};

phone number validation with added input

I recently filled out a form and when I got to the phone number textBox I noticed some really cool things going on. As I entered my number, general phone symbols were getting added automatically. Example:
I start entering my area code '555'
and my input was changed to 1 (555)
to test what just happened I backspaced on the ) and it quickly added it back in.
So my question is, how do I get this input to happen?
I use a javascript library called automask - you dont see the mask but it wont let you type anything outside the mask
for instance if your mask is ###-###-#### then any other characters are ignored (ie not 0-9) and the dashes are put in automatically.
I can post the library if you would like to take a look at
example of implementation
<input type=text name=ssn onkeypress="return autoMask(this,event, '###-##-####');">
// email kireol at yahoo.com
// autoMask - an adaption of anyMask
//
// this will force #'s, not allowing alphas where the #'s are, and auto add -'s
function autoMask(field, event, sMask) {
//var sMask = "**?##?####";
var KeyTyped = String.fromCharCode(getKeyCode(event));
var targ = getTarget(event);
keyCount = targ.value.length;
if (getKeyCode(event) < 32)
{
return true;
}
if(keyCount == sMask.length && getKeyCode(event) > 32)
{
return false;
}
if ((sMask.charAt(keyCount+1) != '#') && (sMask.charAt(keyCount+1) != 'A' ) && (sMask.charAt(keyCount+1) != '~' ))
{
field.value = field.value + KeyTyped + sMask.charAt(keyCount+1);
return false;
}
if (sMask.charAt(keyCount) == '*')
return true;
if (sMask.charAt(keyCount) == KeyTyped)
{
return true;
}
if ((sMask.charAt(keyCount) == '~') && isNumeric_plusdash(KeyTyped))
return true;
if ((sMask.charAt(keyCount) == '#') && isNumeric(KeyTyped))
return true;
if ((sMask.charAt(keyCount) == 'A') && isAlpha(KeyTyped))
return true;
if ((sMask.charAt(keyCount+1) == '?') )
{
field.value = field.value + KeyTyped + sMask.charAt(keyCount+1);
return true;
}
return false;
}
function getTarget(e) {
// IE5
if (e.srcElement) {
return e.srcElement;
}
if (e.target) {
return e.target;
}
}
function getKeyCode(e) {
//IE5
if (e.srcElement) {
return e.keyCode
}
// NC5
if (e.target) {
return e.which
}
}
function isNumeric(c)
{
var sNumbers = "01234567890";
if (sNumbers.indexOf(c) == -1)
return false;
else
return true;
}
function isNumeric_plusdash(c)
{
var sNumbers = "01234567890-";
if (sNumbers.indexOf(c) == -1)
return false;
else
return true;
}
function isAlpha(c)
{
var lCode = c.charCodeAt(0);
if (lCode >= 65 && lCode <= 122 )
{
return true;
}
else
return false;
}
function isPunct(c)
{
var lCode = c.charCodeAt(0);
if (lCode >= 32 && lCode <= 47 )
{
return true;
}
else
return false;
}
If this was an aspx page, they were probably using the AJAX Control Toolkit MaskedEdit Extender. There is also the Masked Input plugin for jQuery.

Categories