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/
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
}
I've been trying to tell the browser to redirect the user to a different location after they close the alert box but none of the methods i have tried seems to be working, so i'm asking you if you can check my code and tell me if you see a possible solution to my needs. This code is just an exercise, I'm practicing and testing javascript.
So far i have tried using these, but nothing's worked.
window.location.href();
window.location.replace();
window.location.assign();
location.href();
location.replace();
location.assign();
HTML code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="javascript.js"></script>
</head>
<body>
<div id="container" align="center"><br />
<form>
Nickname: <input type="text" id="nickname" name="nickname"><br />
Password: <input type="password" id="password" name="password"><br />
<button onclick="login();">Login</button>
</form>
<p id="result:"></p><br />
</div>
</body>
</html>
Javascript Code:
function login(){
var nickname = document.getElementById("nickname").value;
var password = document.getElementById("password").value;
var result = document.getElementById("result");
var error = "Invalid Credentials!";
var sucess = "Login Sucess!";
if (nickname == "neo", password == 123){
alert(sucess);
location.assign("welcome.html");
}
else if(nickname == 22){
confirm("Awesome!");
location.replace("welcome.html");
}
else if(nickname == ""){
alert("Nickname is required!");
}
else{
alert(error);
}
}
You should be using window.location.href as an assignment (using =) rather than treating it as a function (using ()):
if (nickname == "neo", password == 123){
alert(sucess);
window.location.href = "welcome.html";
}
else if(nickname == 22){
confirm("Awesome!");
window.location.href = "welcome.html";
}
Hopefully this helps!
Actually you just need to add type="button" to the button and your code will work:
<button type="button" onclick="login();">Login</button>
The reason is that a button act automatically as type="submit" inside a form.
You should try the following
window.location.href = 'welcome.html';
use this JavaScript code:
function login(){
var nickname = document.getElementById("nickname").value;
var password = document.getElementById("password").value;
var result = document.getElementById("result");
var error = "Invalid Credentials!";
var sucess = "Login Sucess!";
if (nickname == "neo", password == 123){
if (alert(sucess)) {} else {
window.location = "welcome.html";
}
}
else if(nickname == 22){
if (confirm("Awesome!")) {
window.location = "welcome.html";
}
}
else if(nickname == ""){
alert("Nickname is required!");
}
else{
alert(error);
}
}
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!
I have the following script that works fine until I add the other javascript below...
First Script in the header tags
function validateForm() {
var valid = true;
var errMsg = "";
var email = document.emailform.email.value;
var filter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if(email.length <= 0) {
valid = false;
errMsg += "Email address is required.\n";
} else {
if (!filter.test(email)) {
valid = false;
errMsg += "Please provide a valid email address.\n";
}
}
if (errMsg.length > 0) {
alert(errMsg);
return false;
}
}
and just before the closing tags I have...
$('#form').submit(validateForm);
The above works fine, except once I add the script below, validateForm no longer works. This following is added just before the closing body tags.
cbr202=Math.random()*10000000000000000;document.write('<scr'+'ipt language="JavaScript" src="http://example.com/landing.php?lpip=411&202cb='+cbr202+'" type="text/javascript"></scr' + 'ipt>');
I can't seem to figure out what's causing the issue. Hoping someone with experience can see the problem.
Solved: I figured it out... it was due to my own sloppiness. I should have the jquery event handler below the document.write script, not above it.
You forgot to add a closing } to the function. That caused an error and resulted in any JS coming after that to not execute.
function validateForm() {
var valid = true;
var errMsg = "";
var email = document.emailform.email.value;
var filter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if(email.length <= 0) {
valid = false;
errMsg += "Email address is required.\n";
} else {
if (!filter.test(email)) {
valid = false;
errMsg += "Please provide a valid email address.\n";
}
}
if (errMsg.length > 0) {
alert(errMsg);
return false;
}
}
the url generated by
src="http://mysite.com/landing.php?lpip=411&202cb='+cbr202
does not exist. The browser tries to load the script from the url using a get request and fails.
cbr202=Math.random()*10000000000000000;
I think you need change code same below
var cbr202=Math.random()*10000000000000000;
I need a Javascript application that, when run, prompts a password to be entered, and if the password is correct, the script causes the webpage to close. If the password is incorrect, the script prompts for the password to be entered again.
I'm planning on loading this script onto my cell phone, which doesn't have a password-protected keylock feature.
Don't know if this works on your cell phone, but it does with my browser:
<head>
<script language="JavaScript">
var pass_entered;
var password="cool";
while (pass_entered!=password) {
pass_entered=prompt('Please enter the password:','');
}
self.close();
</script>
</head>
Javascript "keylock" on a cell phone will probably be trivial to work around.
Anyway, if you really want to check password in Javascript, you can at least avoid putting it in plain text in page source.
Get MD5 JS implementation, and compare (salted!) password hashes instead.
Ok, we can have two approuches.
We can all read javascript, so if the person actually open your code he will see the password.
By ajax, check the password in a specific page.
function passWrdAPI() {
this.getHX = function() {
var hx;
try {
hx = new XMLHttpRequest();
}
catch(e) {
try {
hx = new ActiveXObject("Microsoft.XMLHttp");
}
catch(ex) {
hx = new ActiveXObject("Msxml2.XMLHttp");
}
}
return hx;
}
this.password = "mypass";
this.checkPwd = function(pass) {
if (pass != this.password) {
// Or close or redirect
alert('Wrong!');
window.close(); //or
location.href = 'http://www.google.com';
}
}
this.checkPwdPage(page, pass) {
var hx = this.getHX();
if (hx != null) {
hx.open('GET',page + "?mypwd=" + pass);
hx.onreadystatechange = function() {
if (hx.readyState == 4) {
if (hx.responseText == 'false') {
// Or close or redirect
alert('Wrong!');
window.close(); //or
location.href = 'http://www.google.com';
}
}
}
hx.send(null);
}
else {
alert('error!');
}
}
}
Usage:
for the first approach:
var check = new passWrdAPI();
check.checkPwd(THEPASSENTERED);
for the second:
var check = new passWrdAPI();
check.checkPwdPage(YOURPAGE, THEPASS);
I don't know if it will work on your cell phone =/
Sorry if I don't help.. bye bye!