reload a page onclick - javascript

I have a simple log on page here: www.mrpbennett.com. I am looking to refresh the page so it removes my password and user name. I currently have the following:
<button class="btn btn-signin" type="button" onclick="check(this.form)" value="login">login</button>
function check(form) {
if (form.userid.value == "admin" && form.pswrd.value == "123qwe!!") {
window.open('http://www.mrpbennett.com/mysite')
}
else {
alert("Error Password or Username")
}
}
This is a super super simple bit of JS but is there anything I can do here to make the page refresh after I have clicked log on? Also is there a way to make the log on button work on pressing enter as well as clicking in?

You should try form.reset() instead. It clears all elements in the target form.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset

USE
window.location.reload();
But, is much better clear the values

Related

How can I modify the content of an HTML page after redirecting from a form using only JavaScript/HTML?

I'm learning HTML and I'm trying to do some very basic stuffs. I have my main page under index.html, a registration form under registration.html, and a script under script.js.
Index.html has the following button: <BUTTON id="login" onclick="register()">login/registration</BUTTON>
function register()
{
if (!loggedIn)
document.location.href = "registration.html";
else
{
// Page not created yet
//document.location.href = "aacount.html";
console.log("redirecting to account page");
}
In script.js, at the top, I have let loggedIn = false;.
The form's submission button looks like this: <button type="submit" class="submit" onclick="submit()"><b>Submit</b></button>
function submit(){loggedIn = true;}
Now on my main page, I have the login button. I would like it to change to an Account button so I made this:
function checkLog()
{
if (loggedIn == true)
document.getElementById("login").textContent = "Account";
else
document.getElementById("login").textContent = "Login/Registration";
}
I want my form, which has the header form class="registration_form" action="index.html" method="post" id="form" to redirect to the main page once you click submit. Since you're now logged in, I want the login/registration to swap to an account button. I don't have any backend because I haven't learned how yet. I just want to modify index.html once it loads back in by using the checkLog() function. Is there a way to do this using only HTML/JavaScript? I have seen a couple solutions using PHP, but I will only jump into it next week once I have more free time. Until then, can I make it work this way?
Just to be sure, I have tried adding onload="checkLog()" to both the entire body text and the login button to no avail. I've also found out that adding onclick="checkLog()" on the submit button in the form doesn't do anything since it executes before the action of changing web pages occur. I basically want a onclick="" that occurs after the action.
As a lot suggested in the comments, since there is no server-side to your project yet you're trying to check if the user is logged in to your website, your best bet is either cookies or LocalStorage. In this answer I will take the LocalStorage approach.
function register()
{
if (localStorage.getItem("userAuthentication") === null)
storage.setItem("userAuthentication", "userAuthentication");
document.getElementById("login").textContent = "Login/Registration";
else {
// User is logged in
// Since the user must have localStorage set up
console.log("redirecting to account page");
document.getElementById("login").textContent = "Account";
}
}
The getItem attribute returns null if the item does not exist; meaning the item hasn't been set yet. if so, we need to set LocalStorage, and change the login button text to "Login/Registration". Else, the localStorage has to be set, meaning we can can change the login button text to "Account".

How would I save input from a text box and then move to the next page? (Javascript/HTML)

As part of my new job, I'm creating a small form where users answer a question and this is then saved and output at the end of the pages.
I started off with having a prompt where users were asked to explain their answers (which worked perfectly!), however I've been asked to change this to an input box.
Essentially the process I need to do is:
User enters in text box -> Clicks next button -> save input to session variable and move to next page
So far, I have the following HTML in the body:
<form name="next" action='#' method=post>
Explanation:<input type="text" id="xp" required><br>
<button class="nextButton" onclick="return explanation()">Next</button>
</form>
with the corresponding javascript:
function explanation() {
var exp = document.getElementById('xp').value;
sessionStorage.setItem("p1_reason", exp);
alert(exp);
document.location.href = 'page2.html';
}
So far the result of this is:
The text box is cleared, but nothing is saved or displayed onscreen
The next page is not displayed.
Any help/advice would be appreciated. I'm relatively new to js so I'd be grateful! I'm well aware that there are similar questions around, I just can't seem to see where I'm going wrong.
#David is right. You can add event.preventDefault() function to prevent the form from its default behaviour, which is submitting. Otherwise your code seems to work.
function explanation() {
event.preventDefault(); // <-- add here
var exp = document.getElementById('xp').value;
sessionStorage.setItem("p1_reason", exp);
alert(exp);
window.location.href = 'page2.html';
}
Also, don't use document.location.href, it's deprecated. It's better to use window.location.href instead.
When you click on nextButton, the browser run explanation() and then try to execute the action of your form. Because your action is action='#' it just try to reload the page, preventing document.location.href for working properly.
Actually, you can try to don't enter nothing on the box and click on the button. The redirect will work because the form is empty, so there is nothing to submit.

Windows alert javascript with redirect function

This is my script
<script>
function myAlert() {
alert("You have changed your username, you will be logged out in order changes to be applied");
}
</script>
and this is my button
<input type="submit" value="Save" name="btnPass" class="button" onclick="myAlert()";/>
I wanted to know if there's a way how to add a redirect script when the "okay" button at the alert is click. how can i add it on my script? how can i add it on my script? thanks!
Use confirm instead of alert
The Window.confirm() method displays a modal dialog with an optional message and two buttons, OK and Cancel.
function myAlert() {
var confirmed = confirm("You have changed your username, you will be logged out in order changes to be applied");
// If OK button is clicked
if (confirmed) {
window.location.href = 'google.com';
}
return false; // To stop form from submitting
}
#Tushar is correct on using the confirm dialog. Below is a modified version of his answer sure to work
function myAlert() {
var confirmed = confirm("You have changed your username, you will be logged out in order changes to be applied");
// If OK button is clicked
if (confirmed == true) {
window.open("path-to-logout script","_self");
}
}

Can I/how do I use an OnClick with an if statement in?

I am trying to create a button that when pressed deletes a database entry, when I click it I want a message to say "are you sure you want to delete this" and then if I click cancel the message goes away and nothing happens, if I click okay the deletion runs -- but also it reloads the page, I think this will require a jquery(this is what I would like it to be in ) if statement that basically says if ok is clicked then run the default and also refresh the page after the code has run.
so far I have
<button name="del" type="submit" value="1" onclick="return confirm('Are you sure you want to delete this?') "> delete</button>
Please tell me if I am going the wrong way with this and if I am not, please help me out with how to write the if, (I have infact searched for this and the information is not complete enough for me to understand, I am a PHP developer, never used any Javascript before in my life but would like to start)
EDIT: if this is a caching issue how do I solve it?
The confirmation you have is fine.
However, you're basically performing 2 requests when you press "Ok".
I'd do this one of 2 ways:
1.
Postback to the same page and use PHP to handle the $_POST data before generating the data for the page. Pseudo code:
if($_POST['userid']!= null)
deleteUser($_POST['userid']);
getUsers();
2.
Use Javascript to fire an Ajax request to another page which does the deletion of your user. Then on the "Complete" event, get JS to reload the page that you're currently on.
I think option 2 would be best. It will give you some more exposure to JavaScript too.
$.ajax({
url: "deleteuser.php?userid=1",
}).done(function() {
location.reload();
});
Or the equivilant for $.post
You don't even need to reload the page. You can use Javascript to remove the row containing the user you just deleted.
This of course uses jQuery, but jQuery is just a wrapper for Javascript
I believe your issue is more of a caching issue and reloading the page after a form submission is not efficient since you are performing an unneeded roundtrip to the server, however if that's what you want here's one way of doing it:
PS: Remove the onclick attribute on your submit button.
document.addEventListener('DOMContentLoaded', function () {
initDeletionPage(document.getElementById('the-id-of-the-form-to-target'));
});
function initDeletionPage(deletionForm) {
refreshPageIfNeeded();
deletionForm.addEventListener('submit', onSubmit);
function refreshPageIfNeeded() {
if (sessionStorage.getItem('pageRefreshNeeded')) {
sessionStorage.removeItem('pageRefreshNeeded');
location.reload();
}
}
function onSubmit(e) {
if (!confirmDeletion()) e.preventDefault();
else indicatePageRefreshNeededAfterSubmission();
}
function confirmDeletion() {
return confirm('Are you sure you want to delete this?');
}
function indicatePageRefreshNeededAfterSubmission() {
sessionStorage.setItem('pageRefreshNeeded', true);
}
}
Sorry but I asked for a more Jquery way
Ok...
$(function () {
initDeletionPage('#the-id-of-the-form-to-target');
});
function initDeletionPage(deletionForm) {
refreshPageIfNeeded();
$(deletionForm).submit(onSubmit);
function refreshPageIfNeeded() {
if (sessionStorage.getItem('pageRefreshNeeded')) {
sessionStorage.removeItem('pageRefreshNeeded');
location.reload();
}
}
function onSubmit(e) {
if (!confirmDeletion()) e.preventDefault();
else indicatePageRefreshNeededAfterSubmission();
}
function confirmDeletion() {
return confirm('Are you sure you want to delete this?');
}
function indicatePageRefreshNeededAfterSubmission() {
sessionStorage.setItem('pageRefreshNeeded', true);
}
}

How not to refresh a page from JavaScript?

I am working on a website using asp.Net, and it includes a page called from an iframe.
This page named Districting, has a javascript code in the aspx page.
I created a function, that is executed when "Done" button is clicked. This function tests if the conditions that the user made are true.
If yes, another page is loaded, if no, an alert appears, and nothing happens.
But actually, something is happening: the page is refreshing which is not what I want.
This is the button:
<button id="Button1" onclick="testing()">Done</button>
This is the function testing:
function testing() {
if (conditions are true)
//Go to another page
else{
alert("Wrong decision");
//Stay in the current page without refreshing it
}
}
So all I need is to prevent the page from refreshing when clicking on "Done" button.
Thanks in advance:)
Change your code to
function testing() {
if (conditions are true)
return true;
else{
alert("Wrong decision");
return false;
}
}
and your tag to
<button id="Button1" onclick="return testing()">Done</button>
Also, see How to confirm navigation for a link in a href tag?, as it's very similar.
A button is standard an submit button, so is the button in an form?
If that's true, you can takkle that problem when you define the type of the button:
<button type="button" id="Button1" onclick="testing()">Done</button>
Your javascript function that's firing onclick needs to return false. The following should work:
<button id="Button1" onclick="testing(); return false;">Done</button>

Categories

Resources