I’m making a simple submit button for an email form,when clickling on the submit button and the email is valid,it changes the state of the button from “Subscribe” to Unsubscribe and it hides the form. Till here everything is good,but the problem is that when i click the submit button,it does what i need but after i enter a valid email and it changes the state of the button,the oposite action isnt done and it continues to send the email to localstorage,instead of removing it.
Here i add a non valid email :
And in console log i have this email.
Here i add a valid email without refreshing the page :
And now,when i click unsubscribe,it should remove the email from localStorage and return the form and the state of the button,but instead,it makes the submit action..:
What should i do? I am new in JS and here i use only vanilla js.
The code that use the submit button:
document.querySelector('form').addEventListener('submit', function (e) {
e.preventDefault()
console.log(inputForm.value)
localStorage.setItem('Email', inputForm.value)
subscribeEmail(inputForm.value);
})
The code below is used to mentain the state of the button when refreshing the page:
const unsubscribeToggle = localStorage.getItem('unsubscribeToggle')
if (unsubscribeToggle === 'Subscribed') {
getUnsubscribe()
document.querySelector('form').addEventListener('click', function (e) {
e.preventDefault()
getSubscribe()
localStorage.removeItem('Email')
})
} else {
getSubscribe()
}
}
Below is the code that changes the state of the button :
export const getUnsubscribe = () => {
const subscribeBtn = document.getElementById('subscribeButton')
subscribeBtn.setAttribute('value', 'Unsubscribe')
document.getElementById('emailForm').style.display = 'none'
localStorage.setItem('unsubscribeToggle', 'Subscribed')
}
export const getSubscribe = () => {
const subscribeBtn = document.getElementById('subscribeButton')
subscribeBtn.setAttribute('value', 'Subscribe')
document.getElementById('emailForm').style.display = 'block'
localStorage.setItem('unsubscribeToggle', 'Unsubscribed')
}
export const subscribeEmail = (email) => {
if (validateEmail(email) == true) {
getUnsubscribe();
} else if (validateEmail == false) {
getSubscribe();
}
And here is the validation function :
const VALID_EMAIL_ENDINGS = ['gmail.com', 'outlook.com', 'yandex.ru']
export const validateEmail = (email) => {
if (VALID_EMAIL_ENDINGS.some(v => email.includes(v))) {
return true
} else {
return false
}
}
export { VALID_EMAIL_ENDINGS as validEnding }
I dont understand what is wrong,or is this normally to happen..It gives me the oportunity to “unsubscribe” only after refreshing the page,but i want to subscribe and unsubscribe multiple times without the need of refresh.