I created an web form that captures users email addresses. I have set up the conditions that need to be met in order for a user to be able to submit their email address and I am able to successfully return error messages.
However, if a user produces inputs an invalid code, they are still directed to the next screen after they close out the error.
HTML:
<form class="watch-films" onsubmit="location.href='thankYou_watch.html'">
<p class="paid_in_full">Email</p>
<input class="field2" name="viewerEmail" id="viewerEmail" placeholder="youremail#example.com" required>
<div>
<button type="submit" class="button_done" value="submit">Submit</button>
</div>
</form>
Javascript:
const watchForm = document.querySelector('.watch-films');
const feedback = document.querySelector('.feedback');
const viewerEmailPattern = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
watchForm.addEventListener('submit', e=> {
e.preventDefault();
//validation
const viewerEmail = watchForm.viewerEmail.value;
if(viewerEmailPattern.test(viewerEmail)){
return (true)
} else {
alert("You have entered an invalid email address!")
return (false);
}
console.log(watchForm.viewerEmail.value);
});
Appreciate any help!
You have a submit event handler that redirects the browser to the thank-you page no matter what the result of the other submit event handler is.
onsubmit="location.href='thankYou_watch.html'"
Since it redirects, it will stop the data from being submitted so you won't collect the email address.
Get rid of it entirely.
Have the server-side process that reads the submitted form data generate the thank-you page instead.
Related
I'm still gripping the ropes of HTML, and I was wondering if you could create a basic form that checks if the entered item is correct, then do something like send an alert or redirect to another page. I already know how to create redirects and alerts but I'm just having trouble with the password part. Thanks in advance.
Unfortunately with the nature of JavaScript the password will always be able to obtained from the source code, unless you link it with a backend API Request.
But here is a very simple example with the password opensesame.
function submitHandler(event) {
const formData = new FormData(event.target);
const password = "opensesame";
if (formData.get("password") === password) {
alert("You're In!");
}
event.preventDefault();
return false;
}
const form = document.getElementById("form");
form.addEventListener("submit", submitHandler);
<form id="form">
<label>Password: <input name="password" type="password"></label>
<br><br>
<button type="submit">Submit form</button>
</form>
I currently have a contact form that requires a user to type 'yes' to an agreement. I have knowledge of HTML and CSS, but do not know the possible Javascript code to require the user to enter 'yes' in the text box and to prevent the message from going through if they were to enter 'no' or any other response other than 'yes'. Any assistance would be greatly appreciated. Thank you!
You can use pattern attribute and the form will take care of the validation
<form>
<label for="confirm">Type yes</label>
<input type="text" id="confirm" name="confirm" placeholder="yes" pattern="^yes$" required>
<input type="submit" />
</form>
Simple JavaScript code will look something like
Will run when user tries to submit form
document.getElementByTagName("form").addEventListener("submit", function(event){
//get your input by id:
let input_validate = document.getElementById("your input id");
if(input_validate.value.toUpperCase() !== "YES"){
event.preventDefault();
alert('Please write yes in the input');
return false;
}
});
Hard to give you what you're looking for without more context/your HTML and how you want to handle an input you don't want (error message, prevent form submit, redirect to new page, all of the above). This could go in a function called onchange of the input, or within a function called during form submit.
var response = document.getElementById('[your_inputs_id]').value;
if(response == "yes"){
//do things, or submit, or do nothing
return true;
}
else{
//display error message, don't submit, etc.
return false;
}
I'm trying to create a super simple email validator by using a regular expression. I've checked out similar questions here on SO as well as looking up other solutions elsewhere, like W3resource. I'm not sure if I'm overlooking something or if I have something typed wrong. The problem I'm having is that whether I enter either a correct or incorrect email, nothing happens. Neither of my alerts are working and the page remains blank.
Here is my Javascript code.
function checkmail(inputText)
{
var emailregex = /^\w[-._\w]*\w#\w[._\w]*\w\.\w{2,8}$/;
if(inputText.value.match(emailregex)) {
alert("You have entered a valid email address!");
return true;
} else {
alert("You have entered an invalid email address!");
return false;
}
}
Here is my relevant HTML code.
<div class="mail">
<center>
<p>Please enter an email address.</p>
<form id="inputemail">
<input type='text' name='input'/>
<input type="submit" name="submit" value="Verify" onclick="checkmail(inputText)"/>
</form>
</center>
</div>
<script src="regexobj.js"></script>
</body>
</html>
You need to specify where to get the data from. In your code you have a function that defines a variable "inputText". In your code there is no data being sent to the function and the function fails to get the data and returns an error.
To fix this you need to specify the data that you want to get, for example:
function checkmail(){
var input = document.querySelector("input[name='input']");
var emailregex = /^\w[-._\w]*\w#\w[._\w]*\w\.\w{2,8}$/;
if(input.value.match(emailregex)) {
alert("You have entered a valid email address!");
return true;
} else {
alert("You have entered an invalid email address!");
return false;
}
}
In this example the function will search for an input field with the name of input. input.value will contain the data from the input field.
In your HTML file you need to change the button submit to
<input type="submit" name="submit" value="Verify" onclick="checkmail()"/>
I have tested the above code and it should work accordingly. I hope to have helped with your problem.
Edit:
When submitting the form the page will automatically reload, if you want to stay on the same page and just give an alert you could do the following changes in your HTML file:
Remove the onsubmit property on the Submit button
<input type="submit" name="submit" value="Verify"/>
Add the following onsubmit function to your form
onsubmit="event.preventDefault(); checkmail();"
When you submit the form, the form will first prevent the page from reloading and will then execute your function. When you click on the alert, the page will not reload and remove the values inserted in the form.
Here is my log in page: http://www.flimpact.org/testlogin.html. The script works perfectly if you enter the password and then click the Login button - a popup alert informs you the password is correct and you move on to the next page. However, if you type the correct password and click Enter instead of clicking the Login in button, you get the alert, but it does NOT forward you to the page.
You can test it yourself - the password is: easy
I've tried changing input type="button" to type="submit" and adding onSubmit="Login()" to my form, but then the form completely stopped working.
Any help would be appreciated.
Thanks,
Deborah
I assume you're just storing the password client-side for testing purposes?
However, to get your code working, you have a couple of options. I prefer to use the logIn function as a boolean check to determine if it is successful. Then you need to move the action to the form and change your button to a submit button. This should work for you:
<form name="lform" id="lform" action="http://www.flimpact.org/1staff.html" onSubmit="return logIn()">
<input type="password" class="passwordinput" size="40" name="login" id="login">
<br>
<input type="submit" class="loginbutton" value="Login">
</form>
<script type="text/javascript">
//Powered by DCScript
function logIn() {
var pass = unescape("%65%61%73%79");
switch (document.lform.login.value) {
case pass:
alert("Valid password. Access granted");
return true;
break;
default:
alert("Invalid password. Please try again.");
return false;
}
}
</script>
JS Fiddle Demo
May be you can change your "parent.location" to "window.location.href" : )
Try returning false from your logIn() function and changing your form tag to read:
<form name="lform" id="lform" onsubmit="return logIn()">
I'm using a basic javascript email validation function and am trying to use jQuery to submit the form if conditions are met. However, the submit() function doesn't seem to be running for the email validation is met.
HTML
<form id="profile" action="" method="post">
<input type="text" id="email">\
<span class="error" id="email_err">Email address not valid.</span>
//Other Form data
</form>
<div id="form-submit">Submit</div>
jQuery/Javascript
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
jQuery(document).ready(function($){
$('#form-submit').click(function(){
var email = $('#email').val();
if(!IsEmail(email)){
$('#email_err').show();
$('#email').focus();
}else{
$('#profile').submit();
}
});
}
Now all I want it to do is catch the email validation. Actual form submittal and data writing I would like to handle as I have it set up now where the PHP for writing the data is on the current page (action=""). Originally, it was an actual form submit button but I wanted to try and validate the email without page refresh.
I figure my understanding of the submit() function might be off-point, as what I'm reading seems like it's just a listener for a form submit, but doesn't actually submit the form itself. Is this correct or do I just have a flub up somewhere?
Since you're just validating your form, you can simply return true or false if the form is valid or not.
Some variant of:
$("#profile").submit(function() {
var email = $('#email').val();
if (!IsEmail(email)) {
...
return false; // Form will not submit
}
...
return true; // Form will submit as usual
});
Make sure you use <input type="submit" /> since you're attaching directly to the submit event.