I have this columns on my table:
QuizId QuizName CreatedBy Created ModifiedBy Modified AccessType Status TotalTime PassedScore QuestionCount QuestionTime Description RandomQuestion LagTime AttemptCount AttemptPeriod AdminEmail ResultScaleId Anonymous FullStatistics FullStatisticsOnSuccess FullStatisticsOnFail MailGroupList StartDate EndDate AutoMailToUser ExtraParams ResultTemplateType PassedTemplateId FailedTemplateId PrintPassedTemplateId PrintFailedTemplateId MailPassedTemplateId MailFailedTemplateId CertificateFailedTemplateId CertificatePassedTemplateId AdminMailTemplateId Metadata StartImmediately HideCorrectAnswers Access asset_id AccessPass
and this javascript code
<SCRIPT>
function passWord()
{
var pass1 = prompt('Please Enter Your Password','');
if(pass1 && pass1.toLowerCase() == "mypass")
{
if (YAHOO.ARISoft.validators.alertSummaryValidators.validate()) YAHOO.ARISoft.page.pageManager.submitForm(); return false;
} else {
alert('Incorect password!');
return false;
}
}
</SCRIPT>
The scripts is working fine, but how can i get from mysql head columns "AccessPass" and replace in javascript "mypass" to read every password from every "QuizId".
New code must be something like:
<sql code generate mypass>
<SCRIPT>
function passWord()
{
var pass1 = prompt('Please Enter Your Password','');
if(pass1 && pass1.toLowerCase() == "$mypass")
{
if (YAHOO.ARISoft.validators.alertSummaryValidators.validate()) YAHOO.ARISoft.page.pageManager.submitForm(); return false;
} else {
alert('Incorect password!');
return false;
}
}
</SCRIPT>
Thx a lot!
I resolved myself:
<SCRIPT>
function passWord()
<?php $mypassword = $this->testes->AccessPass; ?>
{
var pass1 = prompt('Insert the password:','');
if(pass1 && pass1.toLowerCase() == "<?php echo $mypassword; ?>")
{
if (YAHOO.ARISoft.validators.alertSummaryValidators.validate()) YAHOO.ARISoft.page.pageManager.submitForm(); return false;
} else {
alert('Invalid Password!');
return false;
}
}
</SCRIPT>
It works great!
Related
I am trying to work on verifying OTP. Here I have two components that are:
Textbox which takes input of OTP. id="txtOTP"
An Status Line (here i have used <i> tag) that shows status of verified OTP. id="statusLine"
I am using JavaScript for this purpose.
function checkOTP()
{
var OTP = "1234";
var txtOTP = document.getElementById('txtOTP');
var statusLine = document.getElementById('statusLine');
var myOTP = txtOTP.value;
if (OTP.value == myOTP)
{
console.log('Entered in Valid OTP');
statusLine.style.display = "inline";
statusLine.style.color = "green";
statusLine.innerHTML = "OTP Verified, Generating Your Pass and Redirecting to the Next Page... ";
console.log('Exit From Valid OTP');
return true;
}
else if (OTP.value != myOTP)
{
console.log('Entered in Invalid OTP');
statusLine.style.display = "inline";
statusLine.style.color = "red";
statusLine.innerHTML = "Invalid OTP. Please Try Again";
console.log('Exit From Invalid OTP');
return false;
}
}
As Per my code it should go to the if's scope if OTP is correct, and it should go to the else's scope if OTP is wrong.
However, it always goes to the else's scope even though I am writing the correct OTP in the textbox. I have even tried this code without using if with the else statement (like else if() { } ).
You need to either change myOTP to a number or use double equals:
var myOTP = parseInt(txtOTP.value);
Or:
if (OTP == myOTP) {...}
Also note that you don't need else if (...) - just use else {...}.
OTP is a Number but you check OTP.value in if/else if statements
function checkOTP()
{
var OTP = 1234;
var txtOTP = document.getElementById('txtOTP');
var statusLine = document.getElementById('statusLine');
var myOTP = txtOTP.value;
if(OTP === myOTP )
{
console.log('Entered in Valid OTP');
statusLine.style.display = "inline";
statusLine.style.color = "green";
statusLine.innerHTML = "OTP Verified, Generating Your Pass and Redirecting to the Next Page... ";
console.log('Exit From Valid OTP');
return true;
}
else if(OTP != myOTP )
{
console.log('Entered in Invalid OTP');
statusLine.style.display = "inline";
statusLine.style.color = "red";
statusLine.innerHTML = "Invalid OTP. Please Try Again";
console.log('Exit From Invalid OTP');
return false;
}
}
Here is a solution. Its based on the comments and previous answers:
function checkOTP() {
var OTP = "1234";
var txtOTP = document.getElementById('txtOTP');
var statusLine = document.getElementById('statusLine');
var myOTP = txtOTP.value;
if (OTP == myOTP) {
console.log('Entered in Valid OTP');
statusLine.style.display = "inline";
statusLine.style.color = "green";
statusLine.innerHTML = "OTP Verified, Generating Your Pass and Redirecting to the Next Page... ";
console.log('Exit From Valid OTP');
return true;
} else {
console.log('Entered in Invalid OTP');
statusLine.style.display = "inline";
statusLine.style.color = "red";
statusLine.innerHTML = "Invalid OTP. Please Try Again";
console.log('Exit From Invalid OTP');
return false;
}
}
You needed to write OTP instead of OTP.value and you don't need and else if for the opposite. Just else will do.
try adding a else statement after the else if since the syntax is :
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
When the browser loads a js file, it's working with document.getElementById("name").
But when I change to jQuery style, which is $("#name"), that particular element doesn't seem to work any more.
This is how I write my script file in the HTML (right above the closing body tag)
<script src="http://code.jquery.com/jquery-latest.min.js"> </script>
<script src="js/form.js"></script>
</body>
Does anyone knows why jQuery doesn't work?
Edit:
It's just simple code, replacing all document.getElementById to $.
But since you asked, this is the original js code that I've used:
function formValidation() {
var name = document.getElementById("name"),
email = document.getElementById("email"),
phone = document.getElementById("phone"),
message = document.getElementById("message"),
nameRe = /[a-zA-Z]/,
emailRe = /^[a-zA-Z0-9._]+#[a-zA-Z0-9.]+\.[a-zA-Z]{2,4}$/,
phoneRe = /[0-9]/,
messageError = "";
document.getElementById("frmContact").onsubmit = function () {
messageError = "";
// Validation for name, email and phone, using regular expression
if (!nameRe.test(name.value)) {
messageError = errorHighlight(name, "Invalid name");
} else if (!emailRe.test(email.value)) {
messageError = errorHighlight(email, "Invalid email");
} else if (!phoneRe.test(phone.value)) {
messageError = errorHighlight(phone, "Invalid phone");
} else if (message.value.length <= 50) {
messageError = errorHighlight(message, "Message must be at least 50 characters");
}
// form validation
if (messageError !== "") {
document.getElementById("errorMessage").innerHTML = messageError;
return false;
}
return true;
};
}
use .val() ex: name.val() or $("#name").val()
if (!nameRe.test(name.val())) {
messageError = errorHighlight(name, "Invalid name");
} else if (!emailRe.test(email.val())) {
messageError = errorHighlight(email, "Invalid email");
} else if (!phoneRe.test(phone.val())) {
messageError = errorHighlight(phone, "Invalid phone");
} else if (message.val().length <= 50) {
messageError = errorHighlight(message, "Message must be at least 50 characters");
}
Following how to use it as a small example:
<!DOCTYPE html>
<html lang="de">
<head>
<title>Welcome</title>
</head>
<body>
<h1>It Works!</h1>
<div id="changethat"></div>
<script src="http://code.jquery.com/jquery-latest.min.js"> </script>
<script>
(function($,undefined){
$('#changethat').html('Changed!');
})(jQuery);
</script>
</body>
</html>
JSFiddle: http://jsfiddle.net/qxamct1n/1/
When I combine my php form validation code with my javascript validation code, the javascript code fails to work when I hit the submit button. It will only validate the first form field and not the 3 others and then php will validate all fields. I don't want the php form validation to do anything until javascript has completed the form validation.
When I use only php or only javascript to validate, then the code works correctly. What am I missing here? Is it something to do with the beginning of the form?
"form name="contactform" id="contactform" method="post"
action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"
onsubmit="return validateentry();">"
Am I supposed to do the php form validation while "action" goes to a different web page?
The javascript code:
function validateemail()
{
var emailentry=document.forms.contactform.email.value;
at=emailentry.indexOf("#");
period=emailentry.lastIndexOf(".");
if(at < 1 || ( period - at < 2 ))
{
alert("Please enter correct email in the format of 'yourmail#yourwebsite.com'")
document.forms.contactform.email.focus();
return false;
}
return(true);
}
function validatephonenumber()
{
var re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/;
var numbers = document.forms.contactform.phone.value;
var verified = re.exec(numbers);
if (!verified)
{
alert("Please enter a phone number in the format of 999-999-9999");
return false;
}
return(true);
}
function validateentry()
{
if(document.forms.contactform.name.value=="")
{
alert("Please provide your name.");
document.forms.contactform.name.focus();
return false;
}
if(document.forms.contactform.company.value=="")
{
alert("Please provide your company name. If you don't have one, simply state
that you don't.");
document.forms.contactform.company.focus();
return false;
}
if(document.forms.contactform.email.value == "")
{
alert("Please provide an Email address.");
document.forms.contactform.email.focus();
return false;
}else{
var validformat=validateemail();
if(validformat==false)
{
return false;
}}
if(document.forms.contactform.phone.value=="")
{
alert("Please provide a phone number in the format 999-999-9999.");
document.forms.contactform.phone.focus();
return false;
}
else if(document.forms.contactform.phone.value.length < 12)
{
alert("Please provide the phone number in the format of 999-999-9999.");
document.forms.contactform.phone.focus();
return false;
}
else
{
var validnumber=validatephonenumber();
if(validnumber==false)
{
return false;
}}
if(document.forms.contactform.msg.value=="")
{
alert("Please provide a message.");
document.forms.contactform.msg.focus();
return false;
}
return(true);
}
It's unclear without more code but based on your comment I am going to guess that you have incorrectly written your php and it's breaking your javascript/html code. Perhaps one of your quotes? Look at the source code of the page and run it through one of the online validation services such as http://validator.w3.org and http://www.jslint.com
Try this:
PHP HTML:
<?php
echo "<form name='contactform' id='contactform' method='post'
action='' onsubmit='return validateentry(this);'>"
...
Validation JavaScript:
function validateemail(e)
{
var emailentry = e.value
, at = emailentry.indexOf("#")
, period = emailentry.lastIndexOf(".");
if(at < 1 || ( period - at < 2 ))
{
alert("Please enter correct email in the format of 'yourmail#yourwebsite.com'")
e.focus();
return false;
}
return true;
}
function validatephonenumber(e)
{
var re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/
, numbers = e.value;
if (!re.exec(numbers))
{
alert("Please enter a phone number in the format of 999-999-9999");
e.focus();
return false;
}
return true;
}
function validateentry(f)
{
if(f.name.value == "")
{
alert("Please provide your name.");
f.name.focus();
return false;
}
if(f.company.value == "")
{
alert("Please provide your company name. If you don't have one, simply state
that you don't.");
f.company.focus();
return false;
}
if(f.email.value == "")
{
alert("Please provide an Email address.");
f.email.focus();
return false;
}
else
{
var validformat = validateemail(f.email);
if(validformat == false)
{
return false;
}
}
if(f.phone.value == "" || f.phone.value.length < 12 || (validnumber = validatephonenumber(f.phone)) == false)
{
alert("Please provide the phone number in the format of 999-999-9999.");
f.phone.focus();
return false;
}
if(f.msg.value == "")
{
alert("Please provide a message.");
f.msg.focus();
return false;
}
return true;
}
I'm writing javascript to validate a business calculator / orderform
another team mate has written the math code, but when I put in my code the whole thing stops.
I can't find my error (I'm more a css/html person)
help?
//Order Detail Variables//
var clientname =document.getElementById(clientname);
var phonenumber =document.getElementById(phoneno);
var deliveryaddress=document.getElementById(deliveryaddress);
var suburb =document.getElementById(suburb);
var postcode =document.getElementById(postcode);
var state =document.getElementById(state);
var deliverydistance = document.getElementById(deldistance);
var bagsordered =document.getElementById(bagsordered);
var orderdetailsarray = new Array();
//validation//
// these are boolean variables that when made true//
//by the validation will allow the calculation and logging to occur//
var clientnamevalid = new Boolean(false);
//Regex Variables//
//these are the regex patterns that are used to //
//confirm that the data is valid//
var alpha = pattern=/^[a-zA-Z\-]+$/;
function validation()
{
function validation();
{console.log (clientname);
if(alpha.test(clientname));
var clientnamevalid = true;
if { clientnamevalid = true;
alert(client name valid); //to be replaced with inline alert
}
else {
alert("client name invalid");
}
}
Edit Updated code:
the vars are now
var clientname =document.getElementById('clientname');
the function:
function validation()
{console.log (clientname);
var clientnamevalid = alpha.test(clientname);
if(clientnamevalid);
{
alert('client name valid')
}
else
{
alert("client name invalid");
}
}
Edit Updated code 2:
<button name="calculate" id="calcbutton" onclick="validate()"> Calculate </button>
function validate()
{console.log (clientname);
var clientnamevalid = alpha.test(clientname);
if(clientnamevalid);
{
alert('client name valid');
}
else
{
alert("client name invalid");
}
if clientnamevalid = true;
{
function calculateorder();
}
}
edit 3:
function validate()
{console.log (clientname);
var clientnamevalid = alpha.test(clientname);
if(clientnamevalid);
{
alert("client name valid"); //edited from single quotations
}
else
{
alert("client name invalid");
}
if (clientnamevalid == true);
{
calculateorder();
}
else
{
alert ("please review form");
}
}
calc order func:
function calculateorder()
{
orderdetailsarray [0] = document.forms["orderform1"] ["clientname"].value;
orderdetailsarray [1] = document.forms["orderform1"] ["phoneno"].value ;
orderdetailsarray [2] = document.forms["orderform1"] ["deliveryaddress"].value;
orderdetailsarray [3] = document.forms["orderform1"] ["suburb"].value;
orderdetailsarray [4] = document.forms["orderform1"] ["postcode"].value;
orderdetailsarray [6] = parseFloat(document.forms["orderform1"] ["deldistance"].value);
orderdetailsarray [7] = parseFloat(document.forms["orderform1"] ["bagsordered"].value);
orderdetailsarray [8] = document.forms["orderform1"] ["orderdate"].value;
//gross calculation
var grossbagcost = orderdetailsarray[7] * millendcost;
grossbagcost = Math.round(grossbagcost *100)/100;
document.forms["resultsform"] ["bagsgross"].value = grossbagcost;
//end gross calculation
//discount amount calculation
if (orderdetailsarray [7] <=50)
{
var discountedbagcost = grossbagcost * discountnil;
document.forms["resultsform"] ["discount"].value = discountedbagcost;
}
else if (orderdetailsarray[7] >50 && orderdetailsarray[7] <100)
{
var discountedbagcost = grossbagcost * discount4percent;
discountedbagcost = Math.round(discountedbagcost *100)/100;
document.forms["resultsform"] ["discount"].value = discountedbagcost;
}
else if (orderdetailsarray[7] >=100)
{
var discountedbagcost = grossbagcost * discount7percent;
discountedbagcost = Math.round(discountedbagcost *100)/100;
document.forms["resultsform"] ["discount"].value = discountedbagcost;
}
updated code with null check
function validate()
{console.log (clientname);
//pattern test
var clientnamevalid == alpha.test(clientname);
if(clientnamevalid);
{
alert("client name valid");
}
else
{
alert("client name invalid");
//null check
}
if (x==null || x=="")
{
alert("Client name cannot be left blank");
clientnamenotnull == false;
}
else
{
clientnamenotnull == true;
}
//is the whole form valid
{
if (clientnamevalid == true)
if (clientnamenotnull) == true)
{
calculateorder();
}
else
{
alert ("please review form");
}
}
This appears to be problem area:
function validation()
{
function validation();
You have function inside another function.
Your function validation() is one big bug.
Did you mean
function validation(clientname)
{
console.log (clientname);
var clientnamevalid = alpha.test(clientname);
if (clientnamevalid)
{
alert('client name valid');
}
else
{
alert("client name invalid");
}
}
And you don't call that function in your code. And remember, parentheses and curly braces position does matter.
Another one, adding to anubhava's answer you need to change all getElementById from
document.getElementById(deldistance);
to
document.getElementById('deldistance');
In addition to anubhava and Surender,
the document.getElementById() get string.. so you need to change all this
//Order Detail Variables//
var clientname =document.getElementById(clientname);
var phonenumber =document.getElementById(phoneno);
var deliveryaddress=document.getElementById(deliveryaddress);
var suburb =document.getElementById(suburb);
var postcode =document.getElementById(postcode);
var state =document.getElementById(state);
var deliverydistance = document.getElementById(deldistance);
var bagsordered =document.getElementById(bagsordered);
and write the parameters between quotes.
for example:
var bagsordered = document.getElementById('bagsordered');
because as you wrote it, it confuse the compiler.
you can't pass the variable you just declare now at the same line you want his id.
if you're a css/html person as you say, you know that when you create an html button or div
you can define his id.
like <input type="button" id="order" value="press to order" />
now in javascript you can add functionality to this button. so when you want to get
this button in javaScript you can use the function document.getElementById('order')
see? I gave the id of the button that was declared in the html code.
hope you understand what i mean
Edit
look, when you have a button, as you said. for example i'll use the button I wrote before.
<input type ="button" id="order" value="press to order"/>
now if I have a function called "function()";
and I want that when the user will press on the button the function will be called
so I'll add to the html code of the button the onclick
so now it will be :
<input type = "button" id="order" value ="press to order" onclick="function()"/>
now when the user will click on that button, the function will be called and the code in it will performed
in addition, when you write a function that will change some label or button text.
you will need to get theirs id.
if my function is "changeText()". and I have a button with value "Hello" and id = "btn"
and I want to change the button value's from "Hello" to "wow"
so I need to get that button right?
and how do I get it?
with the method document.getElementById
here is the code:
function changeText()
{
var btn = document.getElementById('btn');
btn.value = "wow";
}
Edit 2:
clientnamevalid is boolean,right?
so when you want to check if it true or false, you can use the if statement.
if (clientnamevalid == true)
{
// do something, like call to calculateorder
calculateorder();
}
else // it's false
{
// do something else
}
note that you don't have to compare the 'clientnamevalid' variable or all another boolean variable to 'true' or 'false', the if statement does it alone. so you can write
if (clientnamevalid) // means that the clientnamevalid is true
{
calculateorder();
}
else
{
// do something else
}
Edit 3:
** From where you get the client name?! you need to enable the user to enter his name..
So you need a Form.. **
function validate()
{
console.log (clientname);
if (clientname != "" || clientname != null)
{
var clientnamevalid = alpha.test(clientname);
if(clientnamevalid)
{
alert("client name valid");
calculateorder();
}
else
{
alert("client name invalid, please review form");
}
}
else
{
alert("client name can't be empty!");
}
}
Currently I am able to add a new email address to my newsletter table, however I am struggling with the AJAX part of the query, ie. the validation.
Below is my Signup.php file:
<?php
require_once('required/init.php');
require_once('required/settings.php');
require_once('required/database.php');
require_once('required/class.phpmailer.php');
require_once('required/globals.php');
$email = trim($_REQUEST["email"]);
// Check if subscriber exists
$SQL= "select email from tblnewsletter where email='".$email."'";
$result = mysql_query($SQL);
if(!$result) {die('Problem in SQL: '.$SQL);} //just checking if there was a problem with your query
if (mysql_num_rows($result)==1) { // he was subscribed already
echo 'You are subscribed.'; // Change the message if you want.
}
else { // does not exist ==> add to the table
$SQL2= "INSERT into tblnewsletter (email) VALUES ('".$email."')";
mysql_query($SQL2);
echo 'Thank you for subscribing'; // Change the message if you want.
}
?>
and here is my Javascript:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#nlsubmit').on('click', function() {
signup();
return false;
});
});
function trim(str) {
str = str.replace(/^\s*$/, '');
return str;
}
function signup()
{
var emailentered = $("#email").val();
var email = trim(emailentered);
//EMAIL VALIDATION
var goodEmail = email.match(/\b(^(\S+#).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\.info)|(\.sex)|(\.biz)|(\.aero)|(\.coop)|(\.museum)|(\.name)|(\.pro)|(\.arpa)|(\.asia)|(\.cat)|(\.int)|(\.jobs)|(\.tel)|(\.travel)|(\.xxx)|(\..{2,2}))$)\b/gi);
var apos = email.indexOf("#");
dotpos = email.lastIndexOf(".");
lastpos = email.length - 1;
var badEmail = (apos < 1 || dotpos - apos < 2 || lastpos - dotpos < 2);
if (email == "" || !goodEmail || badEmail)
{
//Email address fails
$('myResponse').style.display = 'inline';
$('myResponse').style.color = 'red';
alert('Please enter a valid email');
$('email').focus();
return false;
}
else
{
email = encodeURIComponent(email);
//Email address succeeds
$.ajax({
url: "signup.php?email=" + email,
success: function(result) {
alert('here');
$('#myResponse').show();
$("loading").show();
return false;
}
});
}
}
function showResponse(req) {
$("loading").hide();
$("myResponse").innerHTML = req.responseText;
$("myResponse").style.display = "inline";
$("myResponse").style.color = "blue";
$("submit").show();
$("email").invoke('clear');
}
function showException(req) {
$("myResponse").innerHTML = req.responseText;
alert("An error occured while talking to the server. Please try again.");
$("loading", "myResponse").invoke('hide');
$("submit").show();
$("email").invoke('clear');
}
</script>
The form that is calling all this is as follows:
<form method="post" name="subform" id="subform" action="">
<input type="text" id="email" name="email" value="">
<input type="submit" id="nlsubmit" name="submit" value="Sign up">
<div id="myResponse" style="display:none;"></div>
<div id="loading" style="display:none;"><img src="/images/wait.gif" alt=""></div>
</form>
Like I said the newsletter table is updated great, though I'm needing the user to be notified on the same page if they are already present, if the email is invalid etc.
In your function:
$.ajax({
url: "signup.php?email=" + email,
success: function(result) {
alert('here');
$('#myResponse').show();
$("loading").show();
return false;
}
});
'result' refers to whatever was echoed on signup.php, so if result=="You are subscribed." that means that the email address already exists in the database, otherwise if result=="Thank you for subscribing" the email address is new to the database and the new user subscribed. So the function should look something like this:
$.ajax({
url: "signup.php?email=" + email,
success: function(result) {
if(result=="You are subscribed.")
{
// notify user that email address already exists
}
alert('here');
$('#myResponse').show();
$("loading").show();
return false;
}
});