Issues with JavaScript window.location.href [duplicate] - javascript

This question already has answers here:
window.location.href not working
(4 answers)
Closed 1 year ago.
So I have been working on this little puzzle site and I want the correct password for the textfield to be inside the JS function. Now it does recognize the password already which is good but the issue is that when I try to use window.location.href = "https://www.google.com"; it does not redirect the page to new site. It only "refreshes" the site..
My script is as followed:
<script>
function validate() {
var password = document.forms["passwordform"]["password1"].value;
var realpassword = 'salaisuus'
if (password === realpassword) {
window.location.href = "http://www.google.com";
return true;
} else {
alert("Wrong password")
return false;
}
}
</script>
and the actual form is here:
<form id="passwordform" onSubmit="return validate()">
<div class="form-floating mb-3">
<input type="text" class="form-control" id="floatingInput" name="password1" placeholder="whatwhat">
<label for="floatingInput">PASSWORD</label>
</div>
<button type="submit" class="btn btn-dark">TRY IT</button>
</form>
So as said, it does send the alert for wrong password, but the window.location.href is not working. What am I missing here?

www.stackoverflow.com/q/15759020/14834893 here is the answer of your question. – M.Hassan Nasir
Okey, so being little dummy...
All I need to do is add return false; after window.location.href
Thank you

Related

Javascript Quiz with HTML + CSS [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
****This code is now working.
Thankyou for your input everyone.
The initial problem was that the code would run on page load, and then the second problem was that it refreshed the page on submit
After some input from a few individuals we were able to debug it together and I learned some new things.****
function check(){
let correctAns1 = 'carname = "volvo"';
let input = document.getElementById("q1").value;
let score=0;
if(input.toLowerCase() == correctAns1) {
score++;
alert("That is correct")
alert("You have a total of " + score + " points")
}else{
alert("Incorrect")
};
};
document.getElementById("testForm").addEventListener("submit", function(e){
e.preventDefault();
});
<div id="testForm">
<form onsubmit="check(); return false"><br><br>
<h2>Task 1</h2>
<p>Create a variable called carname and give it a value of Volvo</p>
<input type="text" id="q1" value><br>
<input type="submit" value="Submit">
</form>
</div>
You can keep questions, scores in localstorage in JavaScript.
This information is stored in the browser and works like cookies.
ex: value inserting in localstorage:
localStorage.setItem('myCat', 'Tom');
ex: accessing to value from localstorage:
localStorage.getItem('myCat');
You Can Look:
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
I think you are troubled by that empty screen after submission, if yes, then the reason for that is "On form submit the page gets refreshed/redirected" to stop that use onsubmit = "check(); return false" or handle it with js using event.preventDefault.
Using return false:
onsubmit = "check(); return false"
Source
function check() {
let correctAns1 = 'carname = "Volvo"';
let input = document.getElementById("q1").value;
let score = 0;
if (input == correctAns1) {
score++;
console.log("That is correct")
console.log(score)
} else {
console.log("Incorrect")
};
};
check();
<div id="question1">
<form onsubmit="check(); return false"><br><br>
<h2>Task 1</h2>
<p>Create a variable called carname and give it a value of Volvo</p>
<input type="text" id="q1"><br>
<input type="submit" value="Submit">
</form>
</div>
Using preventDefault and javascript onsubmit:
e.preventDefault();
Source
function check() {
let correctAns1 = 'carname = "Volvo"';
let input = document.getElementById("q1").value;
let score = 0;
if (input == correctAns1) {
score++;
console.log("That is correct")
console.log(score)
} else {
console.log("Incorrect")
};
return false
};
document.getElementById("testForm").addEventListener("submit", function(e){
e.preventDefault();
check();
});
<div id="question1">
<form id="testForm" ><br><br>
<h2>Task 1</h2>
<p>Create a variable called carname and give it a value of Volvo</p>
<input type="text" id="q1"><br>
<input type="submit" value="Submit">
</form>
</div>
For storing, you can use localstorage on client-side. You can have an array/object of questions and answers and convert it into a string using JSON.stringify and store it in localstorage
localStorage.setItem('questionBook', JSON.stringify(questionBookObject));
and retrieve it using getItem and then JSON.parse it to get the object back.
const questionBookObject = localStorage.getItem('questionBook');

First time, password field [duplicate]

This question already has answers here:
Javascript if syntax
(5 answers)
Closed 5 years ago.
It's fixed now.
It's basically a textbox that when the right text is entered should cause something to happen, i have code for it, this is my first time playing around with html. It's not really for anything and just for fun
<body>
<center>
<input id="passfield" type="text" value="" />
<input id="check" type="button" value="Check" onclick="check();"/>
<script>
var field = document.getElementById("passfield").value;
var pass = "password";
function check() {
if field === pass then {
window.location.href = 'the site i want it to go to';
};
};
document.getElementById("check").onclick = check();
</script>
<center>
</body>
The console says: check() isn't a function
You have a couple problems:
You should move the variables field and pass into the function, so that they're defined when the function is called. Otherwise, they won't update - which means field will always be empty (since it was set as soon as the page loaded, when the input's value was '')
Add an event listener in your Javascript, rather than using the 'onclick' attribute. It's nicer because it keeps all of your Javascript together, and you won't have to skim through your HTML every time you hit a JS error.
You have some formatting issues - the if in particular should use the following syntax:
if (condition) {
then do this
} else {
do this
}
You can check out this example on CodePen.
<body>
<center>
<input id="passfield" type="text" value="" />
<input id="check" type="button" value="Check" />
<center>
<script>
function check() {
var field = document.getElementById("passfield").value;
var pass = "password";
if (field === pass) {
window.location.href = "the site i want it to go to";
}
}
document.getElementById("check").addEventListener('click', check)
</script>
</body>

location.href is not working in if sentence in javascript

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;
}

Comparing html text inputs and redirecting to another page using Javascript

I am brand new to Javascript and am just using it to make a simple website for fun. I have tried searching the web but am still stuck, so if you could help me or redirect me towards other help, that would be great.
I am trying to use Javascript to send a user to another html page in my site if their input matches my criteria. So I wanted to use an if/else statement to do this: if the text input equals ODQHVHMJKD, it would send them to page3.html. However when I try this on the browser, nothing happens--it just takes me to an identical page with ?codebox1=f&button1=Submit at the end of the address.
Here is my script section:
<script type="text/javascript">
function testResults (form) {
if (form.codebox1.value == ODQHVHMJKD) {
window.location.pathname = 'page3.html';
}
else {
window.alert("Try again!");
}
};
</script>
Here are my form elements:
<form name="form1" method="GET">
<input name="codebox1" type="text" />
<input name="button1" type="submit" value="Submit" onClick="testResults(this.form)"/>
</form>
Can you help me so that I can get this to work? It's more than likely I've done everything completely wrong--any help is appreciated!
Try this,
function testResults (form) {
if (form.codebox1.value == "ODQHVHMJKD") {
window.location = 'page3.html';
}
else {
window.alert("Try again!");
}
return false;
};
You need to prevent the default action of the form. In the submit event, call e.preventDefault(); or return false In addition, you need quotation marks around ODQHVHMJKD
Js Fiddle: http://jsfiddle.net/prankol57/Ht45t/
Maybe this can help you.
<form name="form" onsubmit="Results()">
<input type="text" name="fname" id="val">
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
function Results() {
var val = document.getElementById('val').value;
if (val == "ODQHVHMJKD") {
window.location = 'page3.html';
} else {
window.alert("Try again!");
}
};
</script>

Validating email client side [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Validate email address in Javascript?
How do I validate email on the client side using javascript when the server side cannot validate? From my understanding Javascript can be turned off so how can this be achieved and prevent me from receiving PCI warnings?
$(document).ready(function() {
var clearMePrevious = "";
// clear input on focus
$("#email").focus(function() {
if($(this).val()==$(this).attr("title")) {
clearMePrevious = $(this).val();
$(this).val("");
}
});
// if field is empty afterward, add text again
$("#email").blur(function() {
if($(this).val()=="") {
$(this).val(clearMePrevious);
}
});
$('#submitemail').click(function() {
app.ajax.load({
reqName : 'emailSubmit',
url: '$httpUrl('Bronto-OptIn')$?email=' + $('#email').val(),
selector : '#emailbox',
callback: function(responseText, textStatus) { }
});
return false;
});
});
<form id="emailsignup_form" name="emailsignup_form" method="post" action="$httpUrl('Bronto-OptIn', 'fid', 'information')$">
<div class="fl"><input class="email-signup-input" type="text" title="Enter Your Email Address" value="Enter Your Email Address" name="email" id="email" /></div>
<div class="fl"><button class="email-signup-btn" value="Submit" name="submitemail" id="submitemail">Submit</button></div>
<div class="clear"> </div>
If client side validation is necessary I would put in a fallback for the case that javascript is not enabled -
<script type="javascript">
/* Wire up form submittal */
</script>
<noscript>
<p>JavaScript is required to use this form, please enable JavaScript in your browser!</p>
</noscript>
See this -
How to detect if JavaScript is disabled?

Categories