I wanna make easy way of page with password.
in javascript when i use any code with "location"(i tried everything.. replace, asign...etc), it didn't work anything!!!!
but instead of location.href, when i used window.open(), it is perfectly working.
but i wanna stay same window... not new tab or new window...
help me...
In Html
<form action="" method="post" name="Please enter the password to continue.">
<div class="WorkPassword">
<input type="password" class="button" id="WorkInputPassword"
name="password" placeholder="Please enter the password"/>
<input type="submit" class="button" id="submit" value="Enter" onClick="goLogin();">
</div>
and in javascript.
var input = document.getElementById( 'WorkInputPassword' );
var goLogin = function () {
var password = input.value;
if (password === '1234') {
location.href="google.com";
return false;
} else {
alert( 'check again' );
input.value = '';
return false;
}
};
If you want to redirect to a new domain you should use the complete address (including the http:// or https://).
location.href="http://google.com";
However in your case it's not enough, since you are inside a submit event of your form, and if you want to cancel that submit event you must use event.preventDefault() inside the function.
So, it should be something like that:
if (password === '1234') {
event.preventDefault();
location.href="http://google.com";
return false;
}
Related
I've been trying to let javascript redirect to another html file using window.location but it keeps reloading. Here is the Javascript
var myStorage = window.localStorage;
let accounts = [{
username: 'admin',
pass: 'admin123!',
email: 'admin#gmail.com'
}];
myStorage.setItem("account", accounts);
//check login account
var checkLogin = function() {
let uname = document.getElementById("Uname").value;
let pass = document.getElementById("Pass").value;
if (uname == "admin" && pass == "admin123!") {
myStorage.setItem("user", {
username: 'admin',
pass: 'admin123!',
email: 'admin#gmail.com'
});
alert("Login admin");
window.location = "../account/myaccount.html";
alert("redirect");
} else {
myStorage.setItem("user", undefined);
document.getElementById("incorrectAccount").style.color = "red";
document.getElementById("incorrectAccount").innerHTML = "Incorrect Username or Password";
}
};
<form id="login" method="post" onsubmit="return checkLogin();">
<div>
<label><b>Username:
</b>
</label>
<input type="text" name="Uname" id="Uname" placeholder="admin"><br><br>
</div>
<div>
<label><b>Password: </b></label>
<input type="Password" name="Pass" id="Pass" placeholder="admin123!"><br><br>
</div>
<div>
<input type="submit" name="log" id="log" value="Log In"></a>
<span id="incorrectAccount"></span>
<br><br>
</div>
<div>
<input type="checkbox" id="check">
<span>Remember me</span>
</div>
<div>
Forgot Password?
<br><br>
Register
</div>
</form>
After typing the same username and the password, the first alert works and then it skips the redirect link and goes straight for the 2nd alert message
Submitting a form will cause the page to load the URL specified in the action attribute, which defaults to the current URL, which gives that effect though.
You must be trigging the JS when you submit the form. The JS runs, then the form submits, and the URL being navigated to changes.
You need to prevent the default behaviour of the form submission event.
e.g.
var checkLogin = function(event){
event.preventDefault();
and
document.querySelector('form').addEventListener('submit', checkLogin);
Re edit.
This is the problem. However, you are using event binding methods from before they introduced addEventListener (which became a standard in November 2000).
If you want to use intrinsic event attributes (I don't recommend them, they have some confusing gotchas) then you need to return false from the event handler.
onsubmit="return checkLogin();"
You are currently returning the return value of checkLogin, but that doesn't have a return statement so it returns undefined. You need to return false and not any falsy value.
function myRedirect() {
location.replace("https://stackoverflow.com")
}
<button onclick="myRedirect()">Replace document</button>
I'm trying to send messaging to the user that a field is required if they fail to input a value. I want the error to be displayed on the field itself, rather than a global error message at the top of the page.
If I do not enter any data into the form, it still allows submission. However, if I do not enter a username but I do enter mismatched passwords, the username field receives the validation message "Passwords do not match".
So, it appears to me, that for some reason my code to check if the input is null is not passing as True and so the function continues to my next condition.
Why isn't this function catching nulls?
<form action="/register" method="post">
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text"
oninput="checkNull(this)" id="username">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password" oninput="checkNull(this)"
id="password">
</div>
<div class="form-group">
<input class="form-control" name="confirmPassword" placeholder="Confirm Password" type="password"
oninput="check(this)" id="confirmPassword">
</div>
<script language='javascript' type='text/javascript'>
function check(input) {
if (input.value != document.getElementById('password').value) {
input.setCustomValidity('Passwords do not match');
} else {
input.setCustomValidity('');
}
}
if (input.value == "" || input.value == null) {
input.setCustomValidity('This field is required');
}
else {
input.setCustomValidity('');
}
</script>
<button class="btn btn-primary" type="submit">Register</button>
</form>
I've tried some additional troubleshooting. I split my functions out, one to check for matching passwords, one to check for no input. I realized that by calling them in the same function I was comparing each to the password which is a problem.
As a sanity check, I then set to check for a specific string "foo". When passing in "foo", the error displays as expected, so I know at least the function is getting called.
I then tried to use "===" to compare the value rather than "==", but that didn't work either.
Code updated to reflect most recent changes.
When submit your form, it is not calling check() function. So, if you not touch any input, they will not be validated.
You can solve this by adding onsubmit="return validate()" to <form /> tag:
<form action="/register" method="post" onsubmit="return validate()">
Your validation function could be simple as:
var isValid = true;
function validate() {
isValid = true;
document.querySelectorAll('.form-control').forEach(check);
return isValid;
}
Notice the return keyword. When return value is false the submitting action will be cancelled. check() function should also mutate isValid variable:
function check(input) {
if (input.value == "" || input.value == null) {
input.setCustomValidity('This field is required');
isValid = false;
}
else if (input.type == 'password' && input.value != document.getElementById('password').value) {
input.setCustomValidity('Passwords do not match');
isValid = false;
}
else {
input.setCustomValidity('');
}
}
Also, you should only check if passwords are the same if you are validating a password input.
You can accomplish this by adding the extra condition to password validation: input.type == 'password'
You are calling your check method onchange, if you do not enter any text in the username field, your check method will not be called. So, the simple way to do this is to add required attribute on all your fields.
If you want to do it using JS, look at onsubmit method that gets triggered when the form's submit button is clicked.
Also, you should have three different methods for validating each of your fields. It will be hard to maintain and you will be cramping up one method with various checks.
You are using deprecated techniques here.. You should never attach a function to a form element in-line (within the html tag).
When it comes to checking password on keyup, you could use something like this with jquery:
var pwInputs = $(this).find('input[type=password]');
$('input[type=password]').keyup(() => {
pwarr = new Array();
pwInputs.each(function() {
pwarr.push($(this));
});
if (pwarr[0].val() != pwarr[1].val()) {
// Do work
}
if (pwarr[0].val() == null || pwarr[0].val() == "" & pwarr[1].val() == null || pwarr[1].val() == "") {
// Do Work
}
});
You could use jquery in a similar fashion to check values on submit.
$('#formid').on('submit', function() { // Do work })
I'm trying to do a form and while the alert is popping up it is still submitting. How do I get it to stop submitting??
function validate() {
var first = document.register.first.value;
if (first == "") {
alert("please enter your name");
first.focus();
return false;
}
return (true);
}
<body>
<form name="register" action="testform.php" onsubmit="return(validate());">
<input type="text" name="first" />
<button type="submit" />Submit
</form>
</body>
You added the parenthesis on return() then return(validate()) which we use () when calling the function so it might be considering return a custom function which returns undefined and when returned the undefined it ignores and continue the execution.
How ever the validate is called but it's response is not returned to the form.
Fixed version:
<head>
<script>
function validate(e) {
var first = document.register.first.value;
console.log(document.register.first)
if( first == "" ) {
alert( "please enter your name" ) ;
return false;
}
return(true);
}
</script>
</head>
<body>
<form name="register" action="testform.php" onsubmit="return validate()">
<input type="text" name="first" />
<button type="submit" >sbmit</button>
</form>
</body>
You are better of using the required attribute on the front end of things. It will 'force' the user to input text into the input field before it is able to submit. Please note that I put quotation marks around the word 'force', because one can just edit the HTML and circumvent the HTML required attribute. Therefore make absolutely sure that you are validating user input on the PHP side as well.
Many tutorials and examples exist for PHP Form Validation, such as this one from W3Schools and this one from Medium.
<form name="register" action="testform.php">
<input type="text" name="first" required/>
<input type="submit" value="Submit"/>
</form>
You have several bugs in your code.
<button> element is not self-closing
you are calling focus on value of the input instead of the input element which throws exception
function validate() {
var input = document.register.first;
var text = input.value;
if( text == "" ) {
alert( "please enter your name" ) ;
input.focus();
return false;
}
return true;
}
I think the issue is with the button's type="submit". Try changing it to type="button", with an onclick function that submits your form if validate() returns true.
edit: Arjan makes a good point, and you should use required. But this answers why the form was submitting.
I want to do a very basic jQuery validation of an email via a regex on submit. My HTML:
<form action="POST" id="form">
<input type="email" id="customer_email" placeholder="email here" />
<input type="submit" />
</form>
JS:
$('#form').submit(function() {
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailinput = $('#customer_email').value();
if (email_reg.test(emailinput) == false) {
window.alert('no good');
}
});
To my understanding, for this to work I need to get the value of the input via email input (which I do on line 4) and run a regex on it.
When submit is clicked, the standard input error appears on the form, and not the window alert. Feel free to view a Codepen outlining this here:
http://codepen.io/anon/pen/oYmJLW?editors=1010
You need to add event.preventDefault() to prevent the actual form submission, and use .val() instead of .value() on the input.
$('#form').submit(function(event) {
event.preventDefault();
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailinput = $('#customer_email').val();
if (email_reg.test(emailinput) == false) {
window.alert('no good');
}
});
By declaring your input as type="email" your browser will do the validity checking (you don't need to do it yourself then), if you want to circumvent that use type="text".
I have the following search form:
<form method="get" action="SearchResults.asp" id="frmSearch" name="frmSearch">
<input id="q" name="q" type="text" size="50" />
<input type="submit" value="Search" id="button1" name="button1" />
</form>
I add Javascript to the form submit event using the following:
window.onload = function(){
var frm = document.getElementById("frmSearch");
if (window.addEventListener){
frm.addEventListener('submit',function() {validate(frm);} ,false);
}else if (window.attachEvent){
frm.attachEvent('onsubmit', function() {validate(frm);} );
}
}
The validate function is as follows:
function validate(frm) {
alert(frm.id);
var inputs = frm.getElementsByTagName("input");
alert(inputs[0].id);
alert(frm.getElementById("q"));
if (frm.getElementById("q").value=='') {
alert("Please enter your search terms.");
frm.getElementById("q").focus();
return false;
}
frm.getElementById("button1").disabled = true;
return true;
}
The validate function runs but apparently errors out as Javascript ignores the line
frm.getElementById("q")
because alert(frm.id); returns form id "frmSearch", alert(inputs[0].id) returns "q" which is the id of the textbox, but alert(frm.getElementById("q")) does not display anything at all, not even empty alert box.
Can anyone help me diagnose the issue?
getElementById is a method of document, not every HTML element. You'd need to call document.getElementById().