I am making a site on google sites.
I have a button made by code that detects if you put a certain value into an input box, it should then load another site. But when I enter that correct value, the object crashes.
I've tried a lot of different things, but nothing works.
<form name="form1" method="GET">
<input name="codebox1" type="text" />
<input name="button1" type="submit" value="Check Code" onClick="return testResults(this.form)"/>
</form>
<script>
function testResults (form) {
if (form.codebox1.value == "Doovhhlqjhbh") {
window.location = 'https://sites.google.com/view/the-mbd-project/There-are-secrets-to-be-discovered';
window.alert("Correct Code. Connecting...");
}
else {
window.alert("Wrong Code, try again!");
}
return false;
};
</script>
window.location = string; is wrong . You should use this to change the browser address. Also, alert must be executed before switching the page
change your function to this:
function testResults(form) {
if (form.codebox1.value == "Doovhhlqjhbh") {
window.alert("Correct Code. Connecting...");
setTimeout(() => {
window.location.href = 'https://sites.google.com/view/the-mbd-project/There-are-secrets-to-be-discovered';
}, 0);
}
else { window.alert("Wrong Code, try again!"); }
return false;
}
Related
I have a form to update a user's profile and I want to alert users when they leave the password field blank.
Currently, when a user leaves the password field blank and submits the form, the alert box will come up. But after clicking the OK button on the alert, the page refreshes and somehow the user updates his password to blank...
Here's my code:
$userProfileForm.on("submit", handleUpdateUserProfile);
async function handleUpdateUserProfile(e) {
e.preventDefault();
const updatedUser = {
name: $("#edit-user-name").val(),
password: $("#edit-user-password").val(),
};
if (!updatedUser.password) {
alert("Password can't be empty!");
// not working. It still refreshes the page and set the password to empty
return false;
} else {
currentUser = await currentUser.updateProfile(updatedUser);
saveUserCredentialsInLocalStorage();
return true;
}
}
I also tried e.preventDefault() but it's not working as well. Please tell me how I can prevent the page reload. Thanks!
Edit:
I changed return false to return true and it works...but I received a warning in the console saying [Violation] 'submit' handler took 1130ms jquery:5229
Could someone help me explain what's going on here?
Here's the new code:
$userProfileForm.on("submit", handleUpdateUserProfile);
async function handleUpdateUserProfile(e) {
e.preventDefault();
const updatedUser = {
name: $("#edit-user-name").val(),
password: $("#edit-user-password").val(),
};
if (!updatedUser.password) {
alert("Password can't be empty!");
// working now, the page doesn't refresh but receives a warning
return true;
} else {
currentUser = await currentUser.updateProfile(updatedUser);
saveUserCredentialsInLocalStorage();
// I have to use reload() to force the page upload
location.reload();
}
}
You do not need to return anything from that code. The e.preventDefault() should handle not submitting -
plain js version
document.getElementById("myForm").addEventListener("submit", asyncsubmit)
async function asyncsubmit(e) {
e.preventDefault();
if (e.target.querySelector("[name=q]").value === "") alert("Don't leave empty")
else console.log(e.target.id)
}
<form id="myForm" action="https://www.google.com/search">
<input type="text" name="q">
<input type="submit" value="search">
</form>
jQuery version
$("#myForm").on("submit", asyncsubmit)
async function asyncsubmit(e) {
e.preventDefault();
if ($(e.target).find("[name=q]").val() ==="") alert("Don't leave empty")
else console.log(e.target.id)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form id="myForm" action="https://www.google.com/search">
<input type="text" name="q">
<input type="submit" value="search">
</form>
I tried to delay for 10 sec before submit form like this but not work. It's will be still return true by not to delay.
<form class="form" method="post" action="" ENCTYPE = "multipart/form-data" onsubmit="return checkform(this);" >
<input type="submit" name="submit" value="OK">
</form>
<script language="JavaScript" type="text/javascript">
function checkform ( form )
{
var test = "1";
setTimeout(function(){
if(test != '0'){
return false;
}
else
{
return true;
}
}, 10000);
}
</script>
I want to know, how to delay on checkform using javascript ?
You must return to the checkForm function. A return inside a callback does not return to the outer function. Even if it did it must be immediate, not 10 seconds later
You could use a flag so you can call the function again inside the delay by submitting the form again
var allowSubmit = false;
function checkform(form) {
if (allowSubmit) {
return true;
} else {
var test = "1";
setTimeout(function() {
if (test === '1') {
// when validation passes resubmit with updated flag
allowSubmit = true;
form.submit();
}
}, 10000);
return false;
}
}
Here is a better way to do it if you have jQuery library included. In your case, the page gets submitted to itself and gets refreshed, so your 10 seconds get reset.
<form class="form" method="post" action="" enctype = "multipart/form-data" >
<input type="submit" name="submit" value="OK">
</form>
$(function(){
$("form").bind("submit", function(e){
e.preventDefault();
e.stopPropagation();
var test = "1";
setTimeout(function(){
if(test != '0'){
//return false;
alert("false");
}else{
alert("true")
//return true;
}
}, 10000);
});
});
So the problem here is that a submit request is has the same outcome as if you were to return something in a function.
For example if you had something like this:
function returnExplanation(){
return 0;
console.log("You will never see me");
}
You will never see the text in the console after the return.
A submit functions the same. although there are a few other ways to make this happen, I made a few adjustments to your code to achieve what you were looking for.
<form class="form" id="submitForm" method="post" action="" ENCTYPE = "multipart/form-data">
<input type="button" name="submit" value="OK">
</form>
<script language="JavaScript" type="text/javascript">
$(document).ready(function () {
$('#submitForm').on('click', function ()
{
var test = 1;
setTimeout(
function ()
{
if (test !== 0)
{
console.log("false");
return false;
} else
{
console.log("true");
return true;
}
}, 10000);
$('#submitForm').submit();
});
});
</script>
The first thing I did was give your form an "id". this allows jQuery (or javascript) to easily decipher exactly which element they should be communicating with.
Next, I removed your "onsubmit" attribute and added the appropriate jQuery to respond to the click event.
After that, I changed your button from a "submit" to a "button" type.
lastly, after the timeout, your form still submits with the line that reads:
$('#submitForm').submit();
I hope this helps you on your way to becoming a better HTML / jQuery programmer.
i don't know why it's n't work , want according to check box value redirect to page or do nothing . and this is the code
<html>
<body>
<form onsubmit= "lol()" >
Checkbox: <input type="checkbox" id="myCheck">
<input type="submit" value="Submit">
</form>
<script>
function lol()
{
if(document.getElementById("myCheck").checked == true)
{
window.location="http://www.google.com";
}
else
{
// want do nothing and stay at same page .
}
}
</script>
</body>
</html>
how can i do it
Two things you need to here if you want to keep the form not doing anything in false condition.
When you call the function you need to use return. So that the form won't submit until it got the return true value.
In your function else part you need to mentioned return=false. It will stop the form submitting.
Javascript:
function lol()
{
if(document.getElementById("myCheck").checked == true)
{
window.location.href="http://www.google.com";
}
else
{
return false;
}
}
HTML
<form onsubmit="return lol()">
Checkbox: <input type="checkbox" id="myCheck"/>
<input type="submit" value="Submit" />
</form>
JSFIDDLE DEMO
You can do it in jquery
$('#myCheck').click(function() {
if($('#myCheck').is(':checked')){
window.location = 'http://www.naveedramzan.com';
}
});
Modify your function:
function lol()
{
if(document.getElementById("myCheck").checked == true)
{
window.location.href="http://www.google.com";
}
else
{
// want do nothing and stay at same page .
}
}
To redirect from one page to another, you use window.location.href, not window.location.
you can also use location.assign() function
function lol()
{
if(document.getElementById("myCheck").checked == true)
{
window.location.assign("http://www.google.com");
}
else
{
// want do nothing and stay at same page .
}
}
You don't want to use a post for this, everything can be handled client side:
<body>
Checkbox: <input type="checkbox" id="myCheck">
<input type="button" value="Submit" onclick="lol()">
<script>
function lol() {
if (document.getElementById("myCheck").checked === true) {
window.location = "http://www.google.com";
}
else {
// want do nothing and stay at same page .
alert("staying on page");
}
}
</script>
</body>
All right so I am doing a javascript code for a login type form and it will lead you to a new page. Here it is:
function submit1()
{
var x=document.getElementById("username");
var y=document.getElementById("password");
if (x.value=="username" && y.value=="password")
{
window.location="Example.php";
}
else
{
window.alert=("The information you have submitted is incorrect and needs to be submitted again!");
}
}
When ever I am hitting the submit button it takes me straight to the page instead of checking to see if it right. Please help!
Thank you in advanced! To let you know this is not a permanet login page!
The easy way to do this would be to use a button input:
<input type="button" value="Check" onclick = "submit1();" />
The alternative is to prevent this default behavior of a submit type input, by making the handler return false. Your HTML would look like this:
<input type="submit" value="Check" onclick = "return submit1();" />
Your function would need to be changed a well (considering the fact that you want it to not redirect). I am assuming you want to preserve data entered, so I am not going to use window.location to redirect. Instead, I am going to allow the form to be submitted:
function submit1()
{
var x=document.getElementById("username");
var y=document.getElementById("password");
if (x.value == "username" && y.value == "password") {
window.alert=("The information you have submitted is incorrect and needs to be submitted again!");
return false;
}
}
<html>
<head>
<title>
Login page
</title>
</head>
<body>
<h1 style="font-family:Comic Sans Ms;text-align="center";font-size:20pt;
color:#00FF00;>
Simple Login Page
</h1>
<form name="login">
Username<input type="text" name="userid"/>
Password<input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form)" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
<script language="javascript">
function check(form)/*function to check userid & password*/
{
/*the following code checkes whether the entered userid and password are matching*/
if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd")
{
window.location="Example.php"; /*opens the target page while Id & password matches*/
}
else
{
alert("Error Password or Username")/*displays error message*/
}
}
</script>
</body>
</html>
The event needs to cancel the default event and return false. This will prevent the form from submitting.
HOWEVER, it should be a non-issue if the form submits anyway, because JavaScript CANNOT be trusted and therefore you MUST validate all input server-side.
<form method="post" action="." id="myform">
<!-- form contents --->
</form>
<script type="text/javascript">
(function () {
var f = document.getElementById('myform'), // get your form element
x = document.getElementById('username'),
y = document.getElementById('password'),
handler;
handler = function (e) {
e.preventDefault(); // stop submit
if (x.value=='username' && y.value=='password') {
window.location = 'Example.php';
} else {
window.alert('The information...');
}
};
// listen to submit event
if ('addEventListener' in f) {
f.addEventListener('submit', handler, false);
} else { // handle also IE...
f.attachEvent('submit', function () {
handler(window.event);
});
}
}());
</script>
anyway it looks like you're trying to check login/password from JS what is not greatest idea (anyone can just look into source and read it)
I am stuck on what I thought was a simple PEBCAK error on my part. I am trying to verify all of my functions are true before I submit a form, but cannot figure for the life of me what is wrong. Below is my javascript code:
function checknewaccount(){
if(emailvalid()&& checkname() && passwordcheck())
{
return true;
}
else{
return false;
}
}
function emailvalid()
{
if(email condition)
{
return true;
}
else {
return false;
}
}
function checkname())
{
if(name condition)
{
return true;
}
else {
return false;
}
}
function passwordcheck(){
if(password condition)
{
return true;
}
else {
return false;
}
}
html below:
<form id="newaccount" name="newaccount" method="post" onSubmit="accountcode.php">
<input type="text" id="email" onBlur="emailvalid()"/>
<input type="text" id="username" onBlur="checkname()" />
<input type="password" id="password" onkeyup="passwordcheck()"/>
<input type="submit" value="New" onClick="return checknewaccount()"/>
</form>
When i click "New, nothing happens, and I know the accountcode.php is not running, because nothing happens on the database end and there are no errors reported.
To sum up, my question is how checknewaccount() does not work? Does it have something to do with how I am calling them?
I am new to javascript so if I am completely off on my implementation, I apologize. Thank you very much for the help!
you've got the form syntax wrong - onsubmit = the name of the js function to call, action = the url...
<form action="accountcode.php" id="newaccount" name="newaccount" method="post" onSubmit="return checknewaccount()">
<input type="text" id="email" onBlur="emailvalid()"/>
<input type="text" id="username" onBlur="checkname()" />
<input type="password" id="password" onkeyup="passwordcheck()"/>
<input type="submit" value="New"/>
</form>
Fully tested code:
<html>
<head>
<script type="text/javascript">
function checknewaccount() {
return emailvalid() && checkname() && passwordcheck();
}
function emailvalid() {
var emailAddress = document.getElementById('email').value;
return (emailAddress=='test');
}
function checkname() {
return true;
}
function passwordcheck() {
return true;
}
</script>
</head>
<body>
<form action="#" onsubmit="return checknewaccount();">
<input type="text" id="email" name="email"/>
<input type="submit"/>
</form>
</body>
</html>
The form in the above code will only submit if the textbox has a value of test
A slightly better implementation would be:
<html>
<head>
<script type="text/javascript">
function checknewaccount() {
if(emailvalid() && checkname() && passwordcheck()) {
return true;
} else {
document.getElementById('validation').innerHTML = 'Validation failed!';
return false;
}
}
function emailvalid() {
var emailAddress = document.getElementById('email').value;
return (emailAddress=='test');
}
function checkname() {
return true;
}
function passwordcheck() {
return true;
}
</script>
</head>
<body>
<div id="validation"></div>
<form action="#" onsubmit="return checknewaccount();">
<input type="text" id="email" name="email"/>
<input type="submit"/>
</form>
</body>
</html>
As this at least tells the user the form wasn't submitted. Even better would be to give the user a more detailed reason why but that's beyond the scope of this question...
This part's fine (I took the liberty of fixing the indentation):
function checknewaccount(){
if(emailvalid()&& checkname() && passwordcheck())
{
return true;
}
else{
return false;
}
}
Although you could improve it:
function checknewaccount(){
return emailvalid() && checkname() && passwordcheck();
}
This part is a syntax error (to put it mildly):
function emailvalid(), checkname(), passwordcheck(){
if(condition){
return true;}
else{return false;}
If that's not a real quote from your code, you'll have to update your question (though I may not be here by then to update this answer). Not much point in asking about code and then quoting pseudo-code in the question. (At the very least, the pseudo-code is missing the final }.)
The same sort of thing is true for your functions in the form:
function emailvalid()
{
if(email condition)
{
return true;
}
else {
return false;
}
}
That's fine (assuming that email condition is still psuedocode), but there's no need for the if:
function emailvalid()
{
return email condition;
}
In terms of "nothing happens," make sure you have debugging tools you can use. Chrome has Dev Tools built in, just press Ctrl+Shift+I. For Firefox, you can install the excellent Firebug. Recent versions of IE have dev tools built into them as well (for older versions you can download a free version of Visual Studio that can plug into the browser). Any of these will tell you about syntax and other errors, let you walk through your code statement-by-statement, etc., which is crucial to figuring out what's happening.
Here's a quickly dashed-off version of what I think you're trying to do. I wouldn't do it this way, but I've made the minimal changes to make it work:
HTML:
<form action="http://www.google.com/search"
method="GET" target="_blank"
onsubmit="return checknewaccount()">
<input type="text" id="email" name='q' onblur="emailvalid()">
<input type="text" id="username" onblur="checkname()" >
<input type="password" id="password" onkeyup="passwordcheck()">
<input type="submit" value="New">
</form>
Notes on that:
As Basiclife pointed out, your form code has issues. Those are fixed above.
Above I've used action="http://www.google.com/search" but of course for you it would be action="accountcode.php" (or at least, I think it would).
Use onsubmit for the form submission handler, not onclick on the submit button. You can't cancel a form submission reliably cross-brower via the submit button's onclick.
In onsubmit, make sure you use return — e.g., onsubmit="return checknewaccount()", not onsubmit="checknewaccount()" — because we want to make sure the event stuff sees the return value. We don't care if the event stuff doesn't see the return value of our other checks (onblur="emailvalid()"), but if we did, we'd need returns there as well.
Only one of the fields above has a name attribute; none of yours do. Only fields with name attributes get submitted with forms. I've only used one name for my example because I only want to submit one field to Google, but for your purposes, you're going to want name attributes on all three fields. This brief article has a discussion of id vs. name and what they're for. You sometimes want both.
I've put the attributes in all lower-case, which is best practice (and required if you want to use XHTML).
However, I've removed the / from the ends of the inputs. This is a bit off-topic, but at the apparent level you're working at, you don't want to try to use XHTML, use HTML. Using XHTML correctly is technically difficult, both in authoring and server configuration, and even then you have to serve it as tag soup to IE or it won't handle it properly. XHTML has its place, but in the vast majority of cases, there's no reason to use it.
With the above combined with the JavaScript below, there's no purpose whatsoever to the handlers on the individual fields. I've left them, though, because I assume you're doing more than just the checks below — there's an example further down showing those handlers doing something useful.
JavaScript:
function checknewaccount() {
return emailvalid() && checkname() && passwordcheck();
}
function emailvalid() {
var element;
// Get the email element
element = document.getElementById('email');
// Obviously not a real check, just do whatever your condition is
return element.value.indexOf('#') > 0;
}
function checkname() {
var element;
// Get the username element
element = document.getElementById('username');
// Obviously not a real check, just do whatever your condition is
return element.value.length > 0;
}
function passwordcheck() {
var element;
// Get the username element
element = document.getElementById('password');
// Obviously not a real check, just do whatever your condition is
return element.value.length > 0;
}
Live copy
Things change slightly if the emailvalid, et. al., functions are going to do something to let the user know the fields are invalid, such as highlighting their labels:
HTML:
<form action="http://www.google.com/search"
method="GET" target="_blank"
onsubmit="return checknewaccount()">
<label>Email:
<input type="text" id="email" name='q' onblur="emailvalid()"></label>
<br><label>Username:
<input type="text" id="username" onblur="checkname()" ></label>
<br><label>Password:
<input type="password" id="password" onkeyup="passwordcheck()"/></label>
<br><input type="submit" value="New">
</form>
JavaScript:
function checknewaccount() {
var result;
// Because we're actually doing something in each of the
// three functions below, on form validation we want to
// call *all* of them, even if the first one fails, so
// they each color their field accordingly. So instead
// of a one-liner with && as in the previous example,
// we ensure we do call each of them:
result = emailvalid();
result = checkname() && result;
result = passwordcheck() && result;
return result;
}
function emailvalid() {
var element, result;
// Get the email element
element = document.getElementById('email');
// Obviously not a real check, just do whatever your condition is
result = element.value.indexOf('#') > 0;
// Update our label and return the result
updateLabel(element, result);
return result;
}
function checkname() {
var element, result;
// Get the username element
element = document.getElementById('username');
// Obviously not a real check, just do whatever your condition is
result = element.value.length > 0;
// Update our label and return the result
updateLabel(element, result);
return result;
}
function passwordcheck() {
var element, result;
// Get the username element
element = document.getElementById('password');
// Obviously not a real check, just do whatever your condition is
result = element.value.length > 0;
// Update our label and return the result
updateLabel(element, result);
return result;
}
function updateLabel(node, valid) {
while (node && node.tagName !== "LABEL") {
node = node.parentNode;
}
if (node) {
node.style.color = valid ? "" : "red";
}
}
Live copy