Very strange javascript issue with booleans - javascript

Booleans will work before setting variables inside a function but not after? The variables are all taken from forms except "status".
Here is the function:
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function signup(){
// if(1==1){ -----When I place this here, the alert comes up.
// alert("yes");
// }
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var c = _("country").value;
var g = _("gender").value;
var a = _("age").value;
var o = _("occ").value;
var status = _("status");
// Nothing below here works
if(u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == "" || a == "" || o == ""){
status.innerHTML = "Fill out all of the form data";
alert("true");
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
}
else if( _("terms").style.display == "none"){
status.innerHTML = "Please view the terms of use";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signupfront.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g+"&a="+a+"&o="+o);
}
}
This function is called by a button, and I want the function to return the messages alongside the button.
<button id="signupbtn" onclick="signup()">Create Account</button>
<span id="status"></span>
main.js contains the following:
function _(x){
return document.getElementById(x);
}
Any help with this would be greatly appreciated as I have been looking at it for hours and cannot figure it out.
Thanks in advance
Here is the html as requested:
<body>
<div id="pageMiddle">
<h3>Create Account</h3>
<form name="signupform" id="signupform" onsubmit="return false;">
<div>Username: </div>
<input id="username" type="text" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16">
<span id="unamestatus"></span>
<div>Email Address:</div>
<input id="email" type="text" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">
<div>Create Password:</div>
<input id="pass1" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>Confirm Password:</div>
<input id="pass2" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>Age:</div>
<input id="age" type="text" onfocus="emptyElement('status')" maxlength="3">
<div>Occupation:</div>
<input id="occ" type="text" onfocus="emptyElement('status')" maxlength="88">
<div>Gender:</div>
<input type="radio" name="gender" value="m">Male
<input type="radio" name="gender" value="f">Female
<div>Country:</div>
<select id="country" onfocus="emptyElement('status')">
//long list of countries here
</select>
<div>
<a href="#" onclick="return false" onmousedown="openTerms()">
View the Terms Of Use
</a>
</div>
<div id="terms" style="display:none;">
<h3>Our Terms Of Use</h3>
<p>v</p>
</div>
<br /><br />
<button id="signupbtn" onclick="signup()">Create Account</button>
<span id="status"></span>
</form>
</div>
</body>

if any of your input fields that you are referencing in the variable declaration do not exist your code will fail, because you are calling .value on an undefined field.
post your HTML and we can figure it out.

Have a look at the gender input
<div>Gender:</div>
<input type="radio" name="gender" value="m">Male
<input type="radio" name="gender" value="f">Female
Here's your mistake
var g = _("gender").value;
The code breaks at the above line because you're trying to get the value of an element with id equals gender, but there's no element with id="gender" attribute.
You need to change the gender input to the following, where the radio buttons have the unique id (genderMale and genderFemale)
<div>Gender:</div>
<input type="radio" name="gender" id="genderMale" value="m">Male
<input type="radio" name="gender" id="genderFemale" value="f">Female
then use the following syntax to assign the value of the selected gender to g variable
var g = "";
if (document.getElementById("genderMale").checked) {
g = _("genderMale").value;
} else if (document.getElementById("genderFemale").checked) {
g = _("genderFemale").value;
}
Below is the modified part of the javascript
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var c = _("country").value;
var a = _("age").value;
var o = _("occ").value;
var status = _("status");
var g = "";
if (document.getElementById("genderMale").checked) {
g = _("genderMale").value;
} else if (document.getElementById("genderFemale").checked) {
g = _("genderFemale").value;
}
if (u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == "" || a == ""
|| o == "") {
status.innerHTML = "Fill out all of the form data";
alert("true");
}
Demo: http://jsfiddle.net/zpeu4fq9/1/

Try using this
if(1===1){
alert("yes");
}
if(u === "" || e === "" || p1 === "" || p2 === "" || c === "" || g === "" || a === "" || o === ""){
status.innerHTML = "Fill out all of the form data";
alert("true");
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
}
Hope this help

Related

Validate and display window alert

how do I validate to ensure a value for total or orderForm have been fill up if not it will display a window alert upon clicking on Submit button ?
It seems the below is not working at all .
Pure JS:
function va(){
var result = false;
var w = document.forms["orderForm"]["companyName"].value;
var x = document.forms["orderForm"]["forename"].value;
var y = document.forms["orderForm"]["surname"].value;
var z = document.forms["orderForm"]["total"].value;
if (x == null || x == "") && (y == null || y == "") && (w == null || w == ""){
window.alert('Name must be Filled out');
result = false;
// } else if (z = < 5){
// window.alert('Please Select A CD');
// return false;
// }else {
// return true;
}
return result;
}
HTML:
<section id="checkCost">
<h3>Total cost</h3>
Total <input type="text" name="total" id="total" size="10" readonly="readonly" />
</section>
<section id="placeOrder">
<h3>Place order</h3>
Your details
Customer Type: <select id="show" name="customerType" onchange="change(this)">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
<div id="retCustDetails" class="custDetails" style="display:none">
Forename <input type="text" name="forename" id="forename" />
Surname <input type="text" name="surname" id="surname" />
</div>
<p><input type="submit" name="submit" value="Order now!" id="sub1" disabled="disabled"/></p>
try this:
if (x == null || x == "") {
window.alert('forename must be Filled out');
result = false;
} else if (y == null || y == "") {
window.alert('surname must be Filled out');
result = false;
} else if (w == null || w == "") {
window.alert('companyName must be Filled out');
result = false;
}
return result;
Try:
if ((x == null || x == "") || (y == null || y == "") || (w == null || w == ""))
EDIT:
Sure thing, original line:
if (x == null || x == "") && (y == null || y == "") && (w == null || w == "")
I did two things. Switch out the && for || and wrap the if condition in an inclusive set of parenthesis (which probably isn't required but I do it for neatness). The original if statement reads as "if condition and condition and condition" meaning all conditions have to return true (i.e. be blank) in order to continue. I believe each of these values are required to validate the form. My proposed if statement would read "if condition or condition or condition" letting the alert box be displayed if any value is empty.

Javascript Validation for Radio Buttons in a form with multiple Validations

I'm having trouble finding a way to validate my Gender choice action buttons. I've made efforts at doing it by saying that the buttons can't be left null, but it still recognises one button as being null and won't let me continue. I've tried different variations of this like saying both male and female aren't selected then return false but it still won't work for me. I'm beginning to think that the method I'm going about it just may not be correct. The main issue you want to look at the below is the two radio buttons but I have included the rest of the code as context for the Javascript. The rest of the code works fine it is only the radio buttons than I'm struggling with. Thanks.
Html
<form action="ReviewPHP.php" name="review" onsubmit="return validateForm()">
<fieldset>
Title: <input type="text" name="Title">
</br>
Email Address: <input type="text" name="Email">
<br/>
Rating: <select name="Rating">
<option value="0"></option>
<option value="1">Excellent</option>
<option value="2">Good</option>
<option value="3">Bad</option>
<option value="4">Awful</option>
</select>
<br/>
<textarea name ="Comments" rows="8" colspan="40">Comments:
</textarea>
<br/>
<input type="radio" name="Gender" id="male" value="male">Male
<input type="radio" name="Gender" id="female" value="female">Female
</fieldset>
<fieldset>
<input class="button" type="submit" value="Submit"/>
</fieldset>
</form>
Javascript
function validateForm()
{ //Variable declarations for form inputs
var t = document.forms["review"]["Title"].value;
var e = document.forms["review"]["Email"].value;
var r = document.forms["review"]["Rating"].value;
var c = document.forms["review"]["Comments"].value;
var b = document.forms["review"]["Gender"].value;
var atsymb = e.indexOf("#");
var dotsymb = e.lastIndexOf(".");
if (t == null || t == "") {
document.getElementById("valAlert").innerHTML = "Title Missing";
return false;
}
else if (e == null || e == "" || atsymb < 1 || dotsymb < atsymb + 2 || dotsymb + 2 >= e.length)
{
document.getElementById("valAlert").innerHTML = "Email Missing";
return false;
}
else if (r == "0") {
document.getElementById("valAlert").innerHTML = "Please Rate the Movie, it's why you're here";
return false;
}
else if (c == null || c == "" || c.length < 10) {
document.getElementById("valAlert").innerHTML = "Reviews gotta be at least 10 characters!";
return false;
}
else if (b == null) {
document.getElementById("valAlert").innerHTML = "Please select Gender";
return false;
}
else {
alert("Review for " + t + " has been submitted, Good Job!");
return true;
}
}
You can use checked property to know if a option is checked.
document.getElementById('male').checked
The document is here:
http://www.w3schools.com/jsref/prop_radio_checked.asp
I guess what you would like to do is something like this:
var b = "";
if (document.getElementById('male').checked) {
b = document.getElementById('male').value;
}else if(document.getElementById('female').checked) {
b = document.getElementById('female').value;
}
if(b == "" | b == null ){
// alert
}
Hope this helps.
You have to check if b is undefined.
if (!b || b == null) {
I pared down the javascript and made a simple working demo:
http://jsfiddle.net/z7e7D/

Why do only some of my javascript functions work

I am using javascript and ajax to validate a register form at the moment the function restrict(elem) and the function checkusername() seem to be working, the ajax is passing checkusername variable to PHP and this checks if the username exists and displays a message to me saying username taken or available but no other fields get validated, this is my javascript
javascript validation clientside b4 going to php
function restrict(elem) {
var tf = _(elem);
var rx = new RegExp;
if (elem === "email") {
rx = /[' "]/gi;
} else if (elem === "username") {
rx = /[^a-z0-9]/gi;
} else if (elem === "mobileNumber") {
rx = /[0-9]/g;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x) {
_(x).innerHTML = "";
}
function checkusername() {
var u = _("username").value;
if (u !== "") {
_("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function () {
if (ajaxReturn(ajax) === true) {
_("unamestatus").innerHTML = ajax.responseText;
}
};
ajax.send("usernamecheck=" + u);
}
}
function signup() {
var u = _("username").value;
var e = _("email").value;
var m = _("mobileNumber").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var ci = _("city").value;
var pc = _("postcode").value;
var c = _("country").value;
var d = _("dateOfBirth").value;
var g = _("gender").value;
var status = _("status");
if (u === "" || e === "" || p1 === "" || p2 === "" || c === "" || g === "" || m === "" || ci === "" || pc === "" || d === "") {
status.innerHTML = "Fill out required fields";
} else if (p1 !== p2) {
status.innerHTML = "Your password fields do not match";
} else if (m !== 11 && !IsNumeric(m)) {
status.innerHTML = "Please enter valid mobile number";
} else if (d === "dd/mm/yyyy") {
status.innerHTML = "Please enter your date of birth";
} else {
//ajax to send form data to php
//hides sign button
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
//wait until php verifies data
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function () {
if (ajaxReturn(ajax) === true) {
//if sign not succesful unhide button
if (ajax.responseText !== "signup_success") {
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0, 0);
_("signupform").innerHTML = "OK " + u + ", check your email inbox and junk mail box at <u>" + e + "</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
};
ajax.send("u=" + u + "&e=" + e + "&p=" + p1 + "&c=" + c + "&g=" + g + "&ci" + ci + "&m" + m + "&pc" + pc + "&d" + d);
}
}
and here is my form
<form name="signupform" id="signupform" onsubmit="return false;">
<div>Username: </div>
<input id="username" type="text" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16">
<span id="unamestatus"></span>
<div>Email Address:</div>
<input id="email" type="email" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">
<div>Create Password:</div>
<input id="pass1" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>Confirm Password:</div>
<input id="pass2" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>First name:</div>
<input id="firstName" type="text" /><br />
<div>Last name:</div>
<input id="lastName" type="text" /><br />
<div>Mobile number*:</div>
<input name="mobileNumber" onfocus="emptyElement('status')" onkeyup="restrict('mobileNumber')" maxlength="16">
<div>Gender:</div>
<select id="gender" onfocus="emptyElement('status')">
<option value=""></option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<div>Country:</div>
<select id="country" onfocus="emptyElement('status')">
<?php include_once("country_list.php"); ?>
</select>
<div>City:</div>
<input id="city" onfocus="emptyElement('status')">
<div>Postcode:</div>
<input id="postcode" onfocus="emptyElement('status')">
<div>Relationship Status*:</div>
<select id="relationshipStatus" >
<option value=""></option>
<option value="Single">Single</option>
<option value="Taken">Taken</option>
</select>
<div>Date of Birth*:</div>
<input id="dateOfBirth" type="date" onfocus="emptyElement('status')">
<button id="signupbtn" onclick="signup()">Create Account</button>
<span id="status"></span>
</form>
Your validation regular expressions won't do what you want:
function restrict(elem) {
var tf = _(elem);
var rx = new RegExp;
if (elem === "email") {
rx = /[' "]/gi;
} else if (elem === "username") {
rx = /[^a-z0-9]/gi;
} else if (elem === "mobileNumber") {
rx = /[0-9]/g;
}
tf.value = tf.value.replace(rx, "");
}
Your expression are set up so that they'll pass validation if any single character in the field value matches the character range. You can stipulate that an entire string consist of characters from a particular range like this:
rx = /^[a-z0-9]*$/;

onsubmit not fired when last entry is correct

Everything works fine when there is nothing in the email input, but as soon as I enter a "valid" email address, it doesn't even fire the function because the alert is never triggered. Any help will be appreciated.
Javascript (js/registration.js):
function validateForm() {
var value1 = document.forms["regForm"]["username"].value;
var value2 = document.forms["regForm"]["pass1"].value;
var value3 = document.forms["regForm"]["pass2"].value;
var value4 = document.forms["regForm"]["email"].value;
var atpos = value4.indexOf("#");
var dotpos = value4.lastIndexOf(".");
var check = true;
if(value1 == null || value1 == "") {
$("#userCheck").html("<img src='images/ico_fail.png'/> Please enter a user name! (25 character limit)");
check = false;
} else $("#userCheck").html("<img src='images/ico_pass.png'/>");
if(value2 == null || value2 == "") {
$("#pass1Check").html("<img src='images/ico_fail.png'/> Please enter a password! (25 character limit)");
check = false;
} else {
if(value2.length < 8) {
$("#pass1Check").html("<img src='images/ico_fail.png'/> Password must be 8 to 25 characters");
check = false;
} else $("#pass1Check").html("<img src='images/ico_pass.png'/>");
}
if(value3 == null || value3 == "") {
$("#pass2Check").html("<img src='images/ico_fail.png'/> Please re-enter your password! (25 character limit)");
check = false;
} else {
if(value3 != value2) {
$("#pass2Check").html("<img src='images/ico_fail.png'/> Password does not match!");
check = false;
} else $("#pass2Check").html("<img src='images/ico_pass.png'/>");
}
if(value4 == null || value4 == "") {
$("#emailCheck").html("<img src='images/ico_fail.png'/> Please enter a valid email!");
check = false;
} else {
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
$("#emailCheck").html("<img src='images/ico_fail.png'/> Please enter a valid email!");
check = false;
} else $("#emailCheck").html("<img src='images/ico_pass.png'/>");
}
alert(check);
return check;
}
HTML:
<form name="regForm" method="post" action="" onsubmit="return validateForm();">
<input type="text" id="uName" name="username" size="25" maxlength="25" value=""/>
<span id="userCheck"> (25 character limit)</span></br>
<input type="password" id="password1" name="pass1" size="25" maxlength="25" value=""/>
<span id="pass1Check"> (25 character limit)</span></br>
<input type="password" id="password2" name="pass2" size="25" maxlength="25" value=""/>
<span id="pass2Check"></span></br>
<input type="text" name="email" size="25" value="" />
<span id="emailCheck"></span></br>
<input type="submit" name="submit" value="Register" />
<input type="hidden" name="perm" value="3" /> <!-- regular user -->
<input type="hidden" name="redirect" value="index.php" />
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="js/registration.js"></script>
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
You dont have x defined here. i think it should be value4.length
The problem is: ReferenceError: x is not defined
At this line:
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {

Javascript - Value not passing to function

So I have this form:
<form name="login" id="login" action="" method="POST" onSubmit="return test()">
<input type="text" size="10" name="username" /><div id="wrongUser"></div>
<br />
<input type="password" size="10" name="password" /><div id="wrongPass"></div>
<br />
<input type="submit" value="submit" name="submit" /><br /><br />
</form>
and these two functions:
function test()
{
var user = document.login.username.value;
var pass = document.login.password.value;
if((user == "" || user == null) && (pass == "" || pass == null))
{
document.getElementById('wrongUser').innerText = "Please Enter Username";
document.getElementById('wrongPass').innerText = "Please Enter Password";
return false;
}
if(checkEmpty(user, 'wrongUser', "Please Enter Username"))
return false
if(checkEmpty(pass, 'wrongPass', "Please Enter Password"))
return false;
return true;
}
function checkEmpty(name, id, output)
{
if(name == "" || name == null)
{
document.getElementById(id).innerText = "";
document.getElementById(id).innerText = output;
return true;
}
else
return false;
}
Now the functions kinda work but not how I would think. If the user only doesn't enter anything (first time) then they get the 2 errors. If the user enter just a username (second time) then the username error should disappear, but it doesn't. If I take it out of the function and replace the variables with their normal values then it works just fine. Why would it change when put in this function?
Put the document.getElementById().innerText = '' in the else, not in the if. Because you only reset the innerText when it's empty, but you would like to reset the tekst if it's not empty:
function checkEmpty( name, id, output ) {
var elem = document.getElementById(id); // it's faster to put the element in a var
if( name === undefined || name == '' name == null )
elem.innerText = output;
return true;
else
elem.innerText = '';
return false;
}

Categories