html form with javascript window.location not working - javascript

I added this code to my website:
<script>
function checkPassword(name, pwd) {
if (name == "jamie") {
if (pwd == "198237645") {
window.location = "member.html"
} else {
document.write("Wrong Password!")
}
} else {
document.write("Wrong Name!")
}
}
</script>
<form action="">
Login Name : <input type="text" name="loginname"><br>
Login Pwd : <input type="password" name="loginpwd"><br>
<input type="submit" onclick="checkPassword(this.form.loginname.value,this.form.loginpwd.value)" value="Login">
</form>
However, after i inserted the correct password & name, i only see the link became:
http://tool-box.weebly.com/test.html?loginname=jamie&loginpwd=198237645
What should i do? if i change window.location="member.html" to document.write("Password Correct!"), it worked correctly.
Please help.

You need to cancel the click action so the form does not submit
onclick="checkPassword(this.form.loginname.value,this.form.loginpwd.value); return false;"
I hope you realize this is NOT secure.

Couple of error in code
a) onclick of submit button doesn't return anything hence the form is submitted each time
b) use window.location.href
<script>
function checkPassword(name, pwd) {
if (name == "jamie") {
if (pwd == "198237645") {
window.location.href = "memeber.html"
} else {
document.write("Wrong Password!")
}
} else {
document.write("Wrong Name!")
}
return false;
}
</script>
<form action="" >
Login Name : <input type="text" name="loginname"><br>
Login Pwd : <input type="password" name="loginpwd"><br>
<input type="submit" onclick = "return checkPassword(this.form.loginname.value,this.form.loginpwd.value)" value="Login">
</form>

Related

JavaScript Email address validation

I am making an HTML form with fields validation using JavaScript. I am stuck on email validation. I searched internet and found something like this-
JS Code
function validateemail() {
var x=document.myform.email.value;
var atposition=x.indexOf("#");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length) {
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
}
}
HTML Code
<body>
<form name="myform" method="post" action="#" onsubmit="return validateemail();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form>
Please explain me this?
Check this i am using something like this i minified some of them
You must Enter Valid Email address something like this Example#example.com
$(document).ready(function() {
$('.insidedivinput').focusout(function() {
$('.insidedivinput').filter(function() {
var emil = $('.insidedivinput').val();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (emil.length == 0) {
$('.fa-check').css('display', 'none');
$('.fa-close').css('display', 'inline');
$('.sendmailbuttontrigger').attr('disabled', 'disabled');
$('.SendEmail').attr('disabled', 'disabled');
} else if (!emailReg.test(emil)) {
$('.SendEmail').attr('disabled', 'disabled');
$('.sendmailbuttontrigger').attr('disabled', 'disabled');
$('.fa-check').css('display', 'none');
$('.fa-close').css('display', 'inline');
} else {
// alert('Thank you for your valid email');
$('.fa-close').css('display', 'none');
$('.sendmailbuttontrigger').removeAttr('disabled');
$('.fa-check').css('display', 'inline');
}
})
});
});
.fa-check{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='email' class='insidedivinput'><i class='fa-check'>Validated</i><i class="fa-close">UnValidated</i>
<button class="sendmailbuttontrigger" disabled>
Send
</button>
If you just want to validate an email address, you can use the validation that's built into HTML:
<form onsubmit="return false;">
<input type="email" required="1">
<input type="submit">
</form>
(Leave out the onsubmit for your own form, of course. It's only in my example to keep you from leaving the page with the form.)
I also searched on the Internet and use this one and it's working.
// email validation
checkEmail = (inputvalue) => {
const pattern = /^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
if (pattern.test(inputvalue)) return true;
return false;
}

Why Javascript window.location can't redirect page if condition is true?

Im just started with javascript and this is for testing.
I have basic login form with username and password, and added some Javascript to pickup username and password values, check them and if its true should redirect me to another html page.
In this case Im used window.location..
Here is the code
function Validate() {
username = document.login.korisnicko.value;
password = document.login.lozinka.value;
if (username == "" || password == "") {
window.alert ("Ne valja");
return false;
}
else if (password.length < 6) {
window.alert("mora biti duze od 6 slova");
return false;
}
else {
window.location = "profil.html";
return true;
}
}
<form name = "login">
<h1 id="greska"></h1>
<p id="greska2"></p>
<label>Korisnicko</label> <br>
<input type ="text" id="korisnicko" name="korisnicko"> <br>
<label>Lozinka</label> <br>
<input type ="password" id="lozinka" name="lozinka"> <br>
<button type = "submit" onclick="Validate();">Submit</button>
</form>
Here's a working fiddle:
http://jsfiddle.net/uLbycrhm/1/
I wouldn't recommend using window.location instead of the proper location.href, and I wouldn't recommend using window.alert instead of alert either (what's the difference?), so I've adjusted that as well. Using return here is unnecessary as well, because your function's tied to an onclick, not an onsubmit.
It's important to know that location is kind of an object, here is a link for your reference: MDN.
you can call function with return keyword
<script>
function Validate() {
username = document.login.korisnicko.value;
password = document.login.lozinka.value;
if (username == "" || password == "") {
alert ("Ne valja");
return false;
}
else if (password.length < 6) {
alert("mora biti duze od 6 slova");
return false;
}
else {
window.location = "profil.html";
return false;
}
}
</script>
<form name = "login" method="REQUEST" action=>
<h1 id="greska"></h1>
<p id="greska2"></p>
<label>Korisnicko</label> <br>
<input type ="text" id="korisnicko" name="korisnicko"> <br>
<label>Lozinka</label> <br>
<input type ="password" id="lozinka" name="lozinka"> <br>
<button type = "submit" onclick="return Validate();">Submit</button>
</form>

OnBlur Validation Requires Onsubmit Button to Be Clicked Twice in Pure Javascript

I have a form which validates password null/blank or not using onblur. And I use a submit button to submit the form. However the submit button needs to be clicked twice before to work. It does not work on the first click after something has been filled in the password box. Below is the code.
With respect to Jquery, I require solution in pure Javascript.
I have tried onkeyup, but that is not a good solution as it will put strain on system, and server (for ajax).
<!DOCTYPE html>
<html>
<body>
<script>
var error_user_password = false;
function checkpw(){
var user_password = document.forms["joinform"]["user_password"].value;
if (user_password == null || user_password == "") {
text = "Password : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_password = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_password = true;
}
}
function submitall() {
checkpw()
if(error_user_password == false) {
return false;
} else {
return true
}
}
</script>
</body>
<form id="joinform" method="post" name="joinform" action="#hello" onsubmit="return submitall()" >
<h2>Join</h2>
<input type="password" name="user_password" id="user_password" placeholder="Password" onblur="checkpw()" />
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>
</html>
OnBlur Validation Requires Onsubmit Button to Be Clicked Twice in Pure Javascript
This happens because the blur event is captured from the onblur event handler and not bubbled to the form submit button.
A full javaScript solution is based on:
addEventListener
activeElement: inside the blur event I check after 10 milliseconds if the submit button get the focus.
My snippet:
var error_user_password = false;
function checkpw(ele, e){
var user_password = document.forms["joinform"]["user_password"].value;
if (user_password == null || user_password == "") {
text = "Password : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_password = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_password = true;
}
}
function submitall(ele, e) {
checkpw();
if(error_user_password == false) {
e.preventDefault();
} else {
console.log('form submitted');
}
}
window.addEventListener('DOMContentLoaded', function(e) {
document.getElementById('user_password').addEventListener('blur', function(e) {
checkpw(this, e);
setTimeout(function() {
if (document.activeElement.id == 'join') {
document.activeElement.click();
}
}, 10);
}, false);
document.getElementById('joinform').addEventListener('submit', function(e) {
submitall(this, e);
}, false);
});
<form id="joinform" method="post" name="joinform" action="#hello">
<h2>Join</h2>
<input type="password" name="user_password" id="user_password" placeholder="Password"/>
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>

Can not submit a form using javascript

The hyper link as a submit button is not working.
I think the error may be this <a href="javascript:subForm('myform')">.
I don't know whether this line accept string 'myform' as parameter.
Thanks for your help.
JS
function valid(form) {
if (form.passwd1.value == "") {
alert("Please enter the password")
form.passwd1.focus()
return false
}
if (form.passwd1.value != form.passwd2.value) {
alert("Passwords do not match");
form.passwd1.focus()
form.passwd1.select()
return false
}
return true
}
function subForm(form){
if( valid(document.form)){
document.form.submit();
}
}
Form
<form action="abc.html" name="myform">
Your name: <input type="text" size="30" />
<p>Choose a password: <input type="password" name="passwd1" /></p>
<p>Verify password: <input type="password" name="passwd2" /></p>
<img src="images/submit.jpg"/>
</form>
Instead of passing the form through as a parameter just validate the fields directly in valid(), i.e.
if (myform.passwd1.value == "") ...
For getting form by formName, you should use document.forms[formName]. Your subForm function should change to:
function subForm(formName) {
var form = document.forms[formName];
if (typeof form !== 'undefined' && valid(form)) {
form.submit();
}
}

"Submit" Form and Direct to Javascript Generated URL

I have a login form that, when completed, sends users to a page with a JavaScript generated URL (allowing me to pass a JavaScript variable to my PHP script using $_GET). However, in order to do that, the Login button is currently 'type="button"'. While everything works, it means that users cannot login by hitting Enter; they must actually click the Login button. Is there a way I can "Submit" the form, while still having it point to the JavaScript generated URL?
This seems like a pretty basic concept, which tells me I might be approaching it the wrong way to begin with. Any guidance is appreciated.
HTML:
<form name="login">
Username: <input type="text" name="user_id"/>
Password: <input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form)" value="Login"/>
</form>
JavaScript:
function check(form) {
var userCredentials = [["jsmith", "smithpassword", "John Smith"], ["jdoe", "doepassword", "Jane Doe"]];
var credCheck = 0;
for (var i = 0; i < userCredentials.length; i++) {
if (userCredentials[i][0] == form.user_id.value) {
credCheck += 1;
var displayName = userCredentials[i][2];
if (userCredentials[i][1] == form.pswrd.value) {
window.open("home.php?display_name=" + displayName, "_self");
} else {
alert('The username and password do not match.');
return false;
}
}
}
if (credCheck == 0) {
alert('The username entered is not valid.');
return false;
} else {
return true;
}
}
Instead of opening php page via javascript, you need to change the form action dynamically to point to your generated url.
HTML:
<form name="login">
Username: <input type="text" name="user_id"/>
Password: <input type="password" name="pswrd"/>
<input type="submit" onclick="check(this.form)" value="Login"/>
</form>
JavaScript: (line 9 & 10 changed)
function check(form) {
var userCredentials = [["jsmith", "smithpassword", "John Smith"], ["jdoe", "doepassword", "Jane Doe"]];
var credCheck = 0;
for (var i = 0; i < userCredentials.length; i++) {
if (userCredentials[i][0] == form.user_id.value) {
credCheck += 1;
var displayName = userCredentials[i][2];
if (userCredentials[i][1] == form.pswrd.value) {
form.action = "home.php?display_name=" + displayName;
return true;
} else {
alert('The username and password do not match.');
return false;
}
}
}
if (credCheck == 0) {
alert('The username entered is not valid.');
return false;
} else {
return true;
}
}
You could try:
<form name="login" onsubmit="check(this)">
Username: <input type="text" name="user_id"/>
Password: <input type="password" name="pswrd"/>
<input type="submit" value="Login"/>
</form>

Categories