How can I keep message values in Javascript - javascript

I am quite new to Javascript, so I ask for help because somehow I get stuck.
I dont want the input field to become empty after a page refresh - with some copy&paste of code parts I could partially solve it by using sessionStorage + setItem / getItem.
Now I would like the corresponding message also not become empty - at the moment it disappears when I refresh the page. What's the easiest way to get the message? Thank you for your help!
javascript:
let userInput;
let messageUserText;
var validUser = false;
onload = function (event) {
userInput = document.getElementById('usernameInput');
messageUserText = document.getElementById('userMsg');
}
function InputUser() {
const userName = usernameInput.value;
let messageUserName = '';
if (userName === '') {
messageUserName = 'EMPTY';
validUser = false;
} else {
messageUserName = 'OK';
validUser = true;
}
//THIS IS THE MESSAGE I WANT TO KEEP
messageUserText.innerHTML = messageUserName;
}
//KEEP INPUT AFTER SITE REFRESH
document.getElementById("usernameInput").value = getSavedValue("usernameInput");
//SAVE VALUE
function saveValue(e){
var id = e.id;
var val = e.value;
sessionStorage.setItem(id, val);
}
//RETURN SAVED VALUE
function getSavedValue (v){
if (!sessionStorage.getItem(v)) {
return "";
}
return sessionStorage.getItem(v);
}
html:
<body>
<form>
<input type="text" id="usernameInput" oninput="InputUser()" onkeyup="saveValue(this)">
</form>
<!-- THIS IS THE MESSAGE I WANT TO KEEP AFTER REFRESH -->
<div class=""><p id="userMsg"></p></div>
<script src="javascript.js"></script>
</body>

I tried a lot and have partially solved it. Now its able to save the input and associated message to keep them after site refresh.
But I need help to keep the message color and the state of the submit button . I made some tries but cannot get it going. Please can someone tell me how to write the code? I commented it below.
Javascript:
.
.
.
onload = function (event) {
userInput = document.getElementById('usernameInput');
messageUserText = document.getElementById('userMsg');
setPasswordButton = document.getElementById('passwordButton');
}
function InputUser() {
const userName = usernameInput.value;
let messageUserName = '';
if (userName === '') {
messageUserText.style.color = 'red';
messageUserName = 'Message 1';
validUser = false;
} else {
messageUserText.style.color = 'green';
messageUserName = 'Message 2';
validUser = true;
}
messageUserText.innerHTML = messageUserName;
//Save Message to sessionStorage
var idUserMsg = userMsg.id;
var valUserMsg = messageUserText.innerHTML;
sessionStorage.setItem(idUserMsg, valUserMsg);
//Save Message Color (messageUserText.style.color)
//How?
//Button Activation
if (validUser) {
setPasswordButton.disabled = false;
} else {
setPasswordButton.disabled = true;
}
//Save Button state (setPasswordButton.disabled)
//How?
}
//Keep Inputs after site refresh
document.getElementById("usernameInput").value = getSavedValue("usernameInput");
document.getElementById("userMsg").innerHTML = getSavedValue("userMsg");
//Keep Message Color How?
//Keep Button state How?
//Save sessionStorage
function saveValue(e){
var id = e.id;
var val = e.value;
sessionStorage.setItem(id, val);
}
//Return from sessionStorage
function getSavedValue (v){
if (!sessionStorage.getItem(v)) {
return "";
}
return sessionStorage.getItem(v);
}

Related

My input in the form gets reset when I hit submit . I also tried using console.log() to test if my code is correct but it nothing shows in console

I am creating a form that asks for email and password and validates it. If it has any error, it pops on the same line. Below is my javascript code for it. When I fill the form and hit submit, the values get reset. Moreover, I do not see anything in the console. I tried using a random code console.log('Hanee') to test my code but nothing gets generated in the console tab. Could anyone tell me what's the issue here?
Also, here's the link to my login form: http://www2.cs.uregina.ca/~hsb833/215a/login.html
document.getElementById("login-form").addEventListener("submit",validateLogin,false);
function validateLogin(event){
var elements = event.currentTarget;
var emailValue = elements[0].value;
var passValue = elements[1].value;
checkEmail(emailValue);
checkPass(passValue);
}
function checkEmail(emailValue){
var regex_email = /^[/w]+#[a-zA-Z]+?\.[a-zA-Z]{2,3}$/;
var index = emailValue.search(regex_email);
var errorEmail = document.getElementById("errorEmail");
var valid = true;
console.log('Hanee');
if(index != 0){
errorEmail.style.display = 'inline';
}
}
function checkPass(passValue){
var password = document.getElementById("password");
var regex_pass = /[\w]+\S/;
var index = passValue.search(regex_pass);
if(passValue.length < 6){
console.log('password is invalid. Minimum length is 6');
errorPassLen.style.display = 'inline';
}
if(index != 0){
console.log('password is invalid. Please make sure there is no spaces in between');
errorPassFormat.style.display = 'inline';
}
}
form is refreshed after being submitted by default. To prevent that, use event.preventDefault(); in your validateLogin
Here is an example of a form with a username and password, maybe it will suit you and you can customize it for your needs
async function tebeFxhr() {
let logfil = 1;
let sotebe= false;
let tes =(logt) => {
return /^[a-zA-Z0-9]+$/ui.test(logt);
}
tes(gtebe)==true ? logfil++ : alert('Login cannot contain characters or spaces')
let textrf =(rutext) => {
return /[а-я]/i.test(rutext);
}
textrf(stebe)==true ? alert('The password cannot contain Cyrillic characters') : logfil++;
stebe.length < 8 ? alert('Password is very short') : logfil++;
stebe===ftebe ? logfil++ : alert('Enter the password 2 times so that they match')
if (logfil === 5){
const data = {data_0:gtebe, data_1:stebe, data_2:ftebe};
const response = await fetch("/form", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then((response) => {
return response.text();
})
.then((sotebe) => {
console.log(sotebe)
if(sotebe==='error-1'){
console.log('error-1')
}
else{
sotebe =='' ? location.replace("../") : alert(sotebe)
}
});
}
}
When submit event is triggered, all values are sent to server and get reset. If you want to prevent this, use event.preventDefault(); inside the event handling function validateLogin(event). Then, the values are not going to be reset!
Still If you want your values to be empty after submission, try below.
elements.forEach(e => e.value = '');

Having an issue with the JS form validator. Console in Chrome shows no errors but the validation is not working

This is supposed to handle the form validation for a simple contact form with name, email address, website url, and 10 line comment section for project description, then hand the information as a JSON object to a php file to send to a designated email address.
When I had action="emailprocessor.php in the HTML code, the form validation went through the PHP file and not JS, and it sent properly to the designated email address.
Without the action in the html, it's supposed to flow through the JS and then to the PHP. It's not doing that.
Here is my code:
(function () {
"use strict";
const contactForm = document.getElementById('contactform');
contactForm.addEventListener('submit', validateForm);
//Messages to be put in the message element when there is an error or success...
// The last element in this array loads the preloader css.
const feedBackMessage = [
'<div class="error"><h3>Ooops!</h3><p>The name field is reqired, that\'s how I know who you are. Please fix that and try again!</p></div>',
'<div class="error"><h3>Ooops!</h3><p>You forgot to give me a valid email address. Please fix that and try again!</p></div>',
'<div class="error"><h3>Ooops!</h3><p>You forgot to enter your website. Please fix that and try again!</p></div>',
'<div class="error"><h3>Ooops!</h3><p>Please enter your project description or comment.</p></div>',
'<div class="success"><h3>Thank you!</h3><p>Your information has been sent, and we will be in touch.</p></div>',
'<div class="preloader"><div class="loading-dot"></div></div>'
];
// The actual form validation function. Added url regex.
function validateForm(event) {
event.preventDefault();
const nameField = document.getElementById('name');
const emailField = document.getElementById('email');
const siteField = document.getElementById('website');
const commentField = document.getElementById('comment');
const reName = /^[a-zA-Z]+(([\'\- ][a-zA-Z])?[a-zA-Z]*)*$/;
const reEmail = /^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)#([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$/;
const reUrl = /^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$/;
let errors = 0;
if (!reName.test(nameField.value)) {
displayMessage(nameField, feedBackMessage[0]);
errors++;
}
else if (!reEmail.test(emailField.value)) {
displayMessage(emailField, feedBackMessage[1]);
errors++;
}
else if (!reUrl.test(siteField.value)) {
displayMessage(siteField, feedBackMessage[2]);
errors++;
}
else if (commentField.value == "") {
displayMessage(commentField, feedBackMessage[3]);
errors++;
}
else if (errors === 0) {
sendData();
}
}
// This displays error / success messages
function displayMessage(field, message) {
document.getElementById('message').className = "show-message";
document.getElementById('message').innerHTML = message;
setTimeout(function () {
document.getElementById('message').classList.add("fadeOutElement");
setTimeout(function () {
if (field != 'success') {
document.getElementById('message').className = "hide-message";
document.getElementById(field.id).focus();
}
else {
document.getElementById('message').setAttribute("class", "hide-message");
document.getElementById('name').value = '';
document.getElementById('email').value = '';
document.getElementById('website').value = '';
document.getElementById('comment').value = '';
}
}, 2000);
}, 2000);
//puts messages in the DOM??
}
function sendData() {
document.getElementById('message').className = "show-message";
document.getElementById('message').innerHTML = feedBackMessage[5];
setTimeout(async () => {
const formdata = new FormData(contactForm);
const fetchPromise = await fetch('emailprocessor.php', { method: 'POST', body: formdata });
const data = await fetchPromise.json();
console.log(data.result);
if (data.result == "success") {
displayMessage('success', feedBackMessage[4]);
}
}, 2000);
}
//actually sends the data asynchronously or so it claims
});

Javascript - confirmation dialog after form submission

I am not a Javascript wiz so need some help with the following. I have a popup asking people to type in their email address. Right now the popup just closes after submission, which isn't a nice user experience. Ideally the text bar and the submission button would disappear, and be replaced by a short comment such as "Thanks, we'll be in touch". Even better would be if the popup would then disappear after "N" seconds.
Can anyone help?
var self = this;
var showDelay = parseInt('[[ bannerShowDelayInMilliseconds ]]' || '0', 10);
setTimeout(function () {
requestAnimationFrame(function () {
if (!self.inPreview && "true" == "{{ 'true' if customer.email else 'false' }}") {
return;
}
self.sdk.track('banner', getEventProperties('show', false));
document.body.insertAdjacentHTML('beforeend', self.html);
var banner = self.banner = document.querySelector('.exponea-subscription-dialog');
self.backdrop = document.querySelector('.exponea-subscription-dialog + .exponea-banner-backdrop');
banner.insertAdjacentHTML('afterbegin', '<style>' + self.style + '</style>');
var form = banner.querySelector('form');
form.onsubmit = function () {
var eventProperties = getEventProperties('subscribe');
var email = (form.email.value || '').toLowerCase();
eventProperties.subscription_email = email;
self.sdk.track('banner', eventProperties);
if (validateEmail(email)) {
self.sdk.update({
email: email
});
document.getElementById("dialogue").innerHTML = "Thank you message";
setTimeout(function(){ removeBanner(); }, 3000);
}
return false;
};
var btnClose = banner.querySelector('.exponea-close');
btnClose.onclick = function () {
removeBanner();
self.sdk.track('banner', getEventProperties('close'));
};
});
}, showDelay);
function getEventProperties(action, interactive) {
return {
action: action,
banner_id: self.data.banner_id,
banner_name: self.data.banner_name,
banner_type: self.data.banner_type,
variant_id: self.data.variant_id,
variant_name: self.data.variant_name,
interaction: interactive !== false ? true : false,
location: window.location.href,
path: window.location.pathname
};
}
function removeBanner() {
if (self.banner) {
self.banner.parentNode.removeChild(self.banner);
}
if (self.backdrop) {
self.backdrop.parentNode.removeChild(self.backdrop);
}
}
function validateEmail(email) {
return email && /^\S+#\S+\.\S+$/.test(email);
}
return {
remove: removeBanner
};
form.onsubmit = function () {
var eventProperties = getEventProperties('subscribe');
var email = (form.email.value || '').toLowerCase();
eventProperties.subscription_email = email;
self.sdk.track('banner', eventProperties);
if (validateEmail(email)) {
self.sdk.update({
email: email
});
document.getElementById("thankYouIdExample").innerHTML = "Thank you message";
setTimeout(function(){ removeBanner(); }, 3000);
}
return false;
Just make sure to place the <div id="thankYouIdExample"></div> at the right place.
Let me know if it works for you m8
You can insert your thanks message in another container, and write something like this:
<div id="container">
<div id="form">
here is the form and everything that belongs here
</div>
<div id="thanks">
here is the thanks message
</div>
</div>
With this, you can set the default style of the thanks div to display: none; in css.
If you reference the container divs in js by their ids, you can change their style from js. The setTimeout() method can be used to time the closing of the dialog box, assuming it is done by the removeBanner() function. You can add these lines:
form.onsubmit = function () {
var eventProperties = getEventProperties('subscribe');
var email = (form.email.value || '').toLowerCase();
eventProperties.subscription_email = email;
self.sdk.track('banner', eventProperties);
if (validateEmail(email)) {
self.sdk.update({
email: email
});
document.getElementById("form").style.display = 'none';
document.getElementById("thanks").style.display = 'block';
setTimeout(function(){removeBanner();}, 5000);
}
return false;
This way you can have a fully pre-customized thanks message.
Use setTimeout
https://www.w3schools.com/jsref/met_win_settimeout.asp
https://developer.mozilla.org/de/docs/Web/API/WindowTimers/setTimeout
form.onsubmit = function() {
var eventProperties = getEventProperties('subscribe')
var email = (form.email.value || '').toLowerCase()
eventProperties.subscription_email = email
self.sdk.track('banner', eventProperties)
if(validateEmail(email)) {
self.sdk.update({
email: email
})
setTimeout(() => {
alert("Thatnk You") // you may want to replace it with a own dialogue system
removeBanner()
}, 5000) // wait 5000 milliseconds or in other words 5 seconds
}
return false
}
Asynchronous version (if you want to return after the 5000 wait):
*only useful if you not directly call the handler
form.onsubmit = async function() {
return Promise((resolve, reject) => {
var eventProperties = getEventProperties('subscribe')
var email = (form.email.value || '').toLowerCase()
eventProperties.subscription_email = email
self.sdk.track('banner', eventProperties)
if(validateEmail(email)) {
self.sdk.update({
email: email
})
setTimeout(() => {
alert("Thatnk You") // you may want to replace it with a own dialogue system
removeBanner()
resolve()
}, 5000) // wait 5000 milliseconds or in other words 5 seconds
}
else reject()
})
}

How to change page with JS in html?

I want when the user successfully sign up it goes to the main page.
I already tried a lot of function but it doesn't work..
code :
var nama = document.getElementById("name");
var email = document.getElementById("email");
var userPw = document.getElementById("pass");
sign up code :
function store(){
var rePass = document.getElementById("re_pass");
if (userPw.value == rePass.value && nama.value != "") {
alert("Berhasil daftar!");
} else {
alert('Coba periksa lagi~');
return;
}
localStorage.setItem('namaUser', nama.value);
localStorage.setItem('emailUser', email.value);
localStorage.setItem('passwordUser', userPw.value);
i tried this function also :
self.location = 'sign in.html';
}
Try this one. make sure to clear the space between in this segment!!! 'sign in.html'
window.location = 'sign in.html'
Try this.
window.location.replace("/");
or
window.location.href = "/";

Can't pull up user info right after entered in indexedDB

I have a register form with an indexedDB. I have resgister/log in working. I've been trying different things to get a new register to login as soon as they register but im not sure what's going. It won't work. The localStorage sets like it should but it won't bring up the user's data.
JS:
function addObject(){
if(confirm('Are you sure you want to resgister?')){
fName = document.getElementById('fName').value;
lName = document.getElementById('lName').value;
userName = document.getElementById('uName').value;
pass = document.getElementById('password').value;
email = document.getElementById('email').value;
dob = document.getElementById('dob').value;
tel = document.getElementById('tel').value;
bio = document.getElementById('bio').value;
terms = document.getElementById('terms').value;
school = document.getElementById('school').value;
//Need loop to find radio button values
radios = document.getElementsByName('gender');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
gender=radios[i].value;
}
}
//set up transaction
var mytransaction = db.transaction(['users'], "readwrite");
//get object store
var myusers = mytransaction.objectStore('users');
//Add item
var request = myusers.put(new getUser(userName,fName,lName,pass,email,dob,tel,bio,terms,school,gender));
}
// Show all results.
if(document.URL.indexOf('admin.html') > -1){
mytransaction.addEventListener('complete', showUsers);
}
//Log in new users
loginCheck(userName,pass);
/*newLocal('user',user); */
//Reset Form Fields
resetForm();
}
This is the functions I use when someone logs in.
function loginCheck(user,pass){
db.transaction("users").objectStore("users").get(user).onsuccess = function(e) {
var loggedUser = e.target.result;
if(!loggedUser){
alert('Sorry, Username does not exist. Please try again.');
}else if(pass !== loggedUser.pw ){
alert('Incorrect log in combination. Please try again.');
}else{
loggedIn(loggedUser);
populateFields(loggedUser);
loginStyle(loggedUser)
}
}
}
function loggedIn(loggedUser){
var u=loggedUser;
alert('Welcome '+u.fn+' '+u.ln+' to Macroplay');
//Set localStorage
var signedin = 'user';
var username = u.userName;
newLocal(signedin,username);
}
function getValues(){
db.transaction("users").objectStore("users").get(localStorage.user).onsuccess = function(e) {
populateFields(e.target.result);
loginStyle(e.target.result)
};
;
}
From what I can see the first part adds the user to the DB and the second portion should behave as is I was just logging normally. But it won't pull up the info from the DB.
I've tried setting the new user to localStorage which is how I recognize a user currently loggedin but that also had no effect.
This is my site: http://www3.carleton.ca/clubs/sissa/html5
It looks like you're using the onsuccess handler in the loginCheck method, but you're not when calling put on the db. My guess would be that you're checking to see if the user exists before it's actually had a chance to be added. Try this:
//Add item
var request = myusers.put(new getUser(userName,fName,lName,pass,email,dob,tel,bio,terms,school,gender));
request.onsuccess = function () {
// Show all results.
if(document.URL.indexOf('admin.html') > -1){
mytransaction.addEventListener('complete', showUsers);
}
//Log in new users
loginCheck(userName,pass);
/*newLocal('user',user); */
//Reset Form Fields
resetForm();
}

Categories