Make an action after two events happened - JS - javascript

Want to change submit button color after email verification and checkbox marked. Added listeners on changes and they work well. But have no idea how to find out when this events are going to happen to launch function what is going to change submit button color.
```
https://jsfiddle.net/nvologdins/brfj2xk1/
```

Here is a basic example of how to do this.
I also changed the logic a bit to update the values if the user changes them again. - #Ultimater mentioned this also.
function setupButton() {
if (validEmail && validCheckbox) {
// add/show/enable submit button or simply change the color
button.style.color = "red";
} else {
// remove/hide/disable submit button revert the changes
button.style.color = "";
}
}
form.input.addEventListener('input', (event)=>{
validEmail = emailRegex.test(event.target.value);
setupButton();
})
form.checkbox.addEventListener('change', (event)=>{
validCheckbox = event.target.checked;
setupButton();
})
I would also suggest a different method to validate the form using the Constraint Validation API.
Every element has a validity check which can easily be accessed on the form element using formElement.checkValidity() and returns true/false if all (required) fields inside the form are filled with valid values.
<form oninput="this.querySelector('#submitButton').disabled = !this.checkValidity();" onsubmit="event.preventDefault(); console.log('Submit prevented but the form seems to be valid.'); return false;">
<fieldset>
<label for="newslettermail">E-Mail</label>
<!-- you could also define a more specific pattern on the email input since email would allow foo#bar as valid mail -->
<input type="email" id="newslettermail" required>
</fieldset>
<fieldset>
<input type="checkbox" id="newsletterAcceptTos" required>
<label for="newsletterAcceptTos">I accept the Terms of Service</label>
</fieldset>
<fieldset>
<label for="textFieldWithPattern">Enter <strong>foo</strong> or <strong>bar</strong></label>
<input type="text" id="textFieldWithPattern" pattern="^(foo|bar)$" required>
</fieldset>
<button type="submit" id="submitButton" disabled>Submit</button>
<button type="submit">Force submit (will show errors on invalid input)</button>
</form>
Using this, the browser for itself checks the values if they contain a valid value.
An input[type=email] with required flag must contain a valid mail address.
A checkbox with required flag, must be checked.
An input with required and a pattern must contain a value matching the regular expression from the pattern-attribute.

No need to create extra variables and listen on two form elements separately... You can check the whole thing and update accordingly only by listening to the form element
let form = document.querySelector('form');
let input = document.getElementById('input');
let checkbox = document.getElementById('checkbox');
let submit = document.getElementById('button');
const emailRegex = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
form.addEventListener('change', (event) => {
if (checkbox.checked && emailRegex.test(input.value)) {
submit.style.color = "red";
} else {
submit.style.color = "black"
}
})
//Update
input.addEventListener('input', () => {
const changeEvent = new Event('change');
form.dispatchEvent(changeEvent)
})
<form class="main__emailAndTerms emailAndTerms">
<div class="emailAndTerms__email">
<input type="text" id="input" placeholder="Type your email address here...">
<label class="emailAndTerms__terms">I agree to <span class="terms__link">terms of service</span>
<input type="checkbox" class="terms__checkbox" id="checkbox">
<span class="terms__checkbox_custom"></span>
</label>
<button type="submit" class="email__submitButton" id="button">Submit</button>
</div>
</form>

Related

Javascript email validation is not working even though the email is valid

I'm making two forms with html and javascript, one for "log in" and one for "register". Im using javascript to check that the inputs on the forms are valid. Im running into an issue where the "email" field on the "log in" form is being validated properly, but the "email" field on my "register" form is not, although they are using nearly identical event listeners to validate the inputs.
this is a condensed version of the code that I am using to do this
<html>
<form class="forms" id="login-form" onsubmit="return false" novalidate>
<h1>Log In</h1>
<div class="form-div">
<label for="email">Your Email:</label>
<input type="email" id="email" name="email" required>
<span class="error"></span>
</div>
<button class="wide-buttons" type="submit">Log In</button>
<p onclick="toggleForms()">Need an account? Click here to sign up!</p>
</form>
<form class="forms" id="register-form" onsubmit="return false" novalidate>
<h1>Register</h1>
<div class="form-div">
<label for="email">Your Email:</label>
<input type="email" id="register-email" name="register-email" required>
<span class="error"></span>
</div>
<button class="wide-buttons" type="submit" onclick="validateRegister()">Sign Up</button>
<p onclick="toggleForms()">Already have an account? Click here to log in!</p>
</form>
<script>
const loginForm = document.getElementById("login-form");
const emailError = document.querySelector("#email + span.error");
const registerForm = document.getElementById('register-form');
const regEmailError = document.querySelector("#register-email + span.error");
loginForm.addEventListener("submit", (event) => {
if (!email.validity.valid) {
emailError.textContent = "You must enter a valid email address";
}
});
registerForm.addEventListener("submit", (event) => {
if (!email.validity.valid) {
regEmailError.textContent = "You must enter a valid email address";
}
});
</script>
Im using event listeners for a "submit" event on each form and the one for "loginForm" Is working the way that I intend it to, but the one for "registerForm" is showing my error message when the email is a valid email or anything else is put into the email field. Im stumped by this considering the listeners are practically identical. I don't need to actually submit the form to anything, I'm just trying to learn how some basic form validation works. This code is a snippet of everything else that I have written, but my passwords, checkboxes, etc. are working fine for me. I just need to know how to get the "registerForm" event listener to work the same way that the "loginForm" one is.
edit: Im aware of the onclick="validateRegister()" on the register form- I have removed this in my code and I am still having the issue.
Any help, constructive criticism, or funny jokes are appreciated.
thanks.
It looks like you are trying to check the validity of the email input element on both forms, but you should be checking the validity of the register-email input element on the registerForm event listener.
Change:
if (!email.validity.valid) {
regEmailError.textContent = "You must enter a valid email address";
}
To:
const registerEmail = document.getElementById('register-email');
if (!registerEmail.validity.valid) {
regEmailError.textContent = "You must enter a valid email address";
}
and it should be ok
Edit1: Ofc you can declare registerEmail above event listener

validating a form using jQuery

I've tried, I've researched, and I still can't figure out how to validate this form using jQuery. I've even tried to check out the jQuery API and I had no luck with it. This shouldn't be as hard as it seems. There are a few id's that i'm not using yet because I want to get what I have so far working before I continue. The best I could find for validating emails is just straight up JavaScript. Here's my code.
$(document).ready(function(){
$("#sendForm").click(function(){
var validForm=true; //set valid flag to true, assume form is valid
//validate customer name field. Field is required
if($("#custName").val()) {
$("#custNameError").html(""); //field value is good, remove any error messages
} else {
$("#custNameError").html("Please enter your name.");
validForm = false;
}
//validate customer phone number. Field is required, must be numeric, must be 10 characters
var inPhone = $("#custPhone").val(); //get the input value of the Phone field
$("#custPhoneError").html(""); //set error message back to empty, assume field is valid
if(!inPhone) {
$("#custPhoneError").html("Please enter your phone number.");
validForm = false;
} else {
//if( !$.isNumeric(inPhone) || Math.round(inPhone) != inPhone ) //if the value is NOT numerice OR not an integer. Rounding technique
if( !$.isNumeric(inPhone) || (inPhone % 1 != 0) ) //if the value is NOT numerice OR not an integer. Modulus technique
{
$("#custPhoneError").html("Phone number must be a number.");
validForm = false;
} else {
if(inPhone.length != 10) {
$("#custPhoneError").html("Phone number must have 10 numbers");
validForm = false;
}
}
}
//ALL VALIDATIONS ARE COMPLETE. If all of the fields are valid we can submit the form. Otherwise display the errors
if(validForm) {
//all values are valid, form is good, submit the form
alert("Valid form will be submitted");
//$("#applicationForm").submit(); //SUBMIT the form to the server
} else {
//form has at least one invalid field
//display form and associated error messages
alert("Invalid form. Display form and error messages");
}
}); //end sendform.click
}); //end .ready
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
label {
width:150px;
display:inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2></h2>
<h3>Form Validation Project - Complaint Form</h3>
<form id="form1" name="form1" method="post" action="">
<p>Please enter the following information in order to process your concerns.</p>
<p>
<label for="custName">Name:</label>
<input type="text" name="custName" id="custName" />
<span id="custNameError" class="errorMsg"></span>
</p>
<p>
<label for="custPhone">Phone Number: </label>
<input type="text" name="custPhone" id="custPhone" />
<span id="custPhoneError" class="errorMsg"></span>
</p>
<p>
<label for = "email">Email:</label>
<input type = "text" name = "emailAdd" id = "emailAdd" />
<span id = "emailError" class = "emailError"></span>
</p>
<p>Please Select Product Group:</p>
<p>
<label>
<input type="radio" name="custProducts" value="books" id="custProducts_0" />
Books
</label>
<br />
<label>
<input type="radio" name="custProducts" value="movies" id="custProducts_1" />
Movies
</label>
<br />
<label>
<input type="radio" name="custProducts" value="electronics" id="custProducts_2" />
Consumer Electronics
</label>
<br />
<label>
<input type="radio" name="custProducts" value="computer" id="custProducts_3" />
Computer
</label>
<br />
</p>
<p>Description of problem: (Limit 200 characters)</p>
<p>
<label for="custComplaint"></label>
<textarea name="custComplaint" id="custComplaint" cols="45" rows="5"></textarea>
</p>
<p>
<input type="submit" name="button" id="button" value="File Complaint" />
<input type="reset" name="button2" id="button2" value="Reset" />
</p>
</form>
<p> </p>
$("#button").click(function(e){
e.preventDefault(); // you need to stop the initial event to have a chance to validate
var validForm=true;
// etc...
You can use jquery.validate.js to validate your forms , it will overcome all your manual efforts to create the validation rules also it is providing the various predefined rules like required,email, minlength and maxlength, etc. So, it will be easier for you to achieve what you need very easily.
https://jqueryvalidation.org/
I have a simple jquery form validation and submission package - see if that's of any help - it's easy to install and you can customise quite a few things: https://github.com/sebastiansulinski/ssd-form
Just to get you started, your submit control in the html has id "button", so you should use $('#button').click, not $('#sendForm').click.
Also, if you want to stay on the page (like to do validations, show errors, etc), you have to prevent the form from submitting automatically when the button is clicked. There are lots of ways to do this, but the easiest way is to just change your button type from submit to button. Ie, replace this:
<input type="submit" name="button" id="button" value="File Complaint" />
with this:
<input type="button" name="button" id="button" value="File Complaint" />
------
That should get you started, at least your code will run, you can use console.log to debug, etc. Good luck.
UPDATE
I should add that if you take my advice, the form will never submit on it's own - that is good if some validation fails and you want to stay on the page and give some error feedback to the user.
When you do want the form to submit, you have to make it happen yourself. Again, there are lots of ways to do this, but the simplest one is probably:
$('#form1').submit();

how to append element in datalist in form using javascript

when I am removing form tag then it is working but after adding form tag from HTML it is not working. following is the code on which I am trying and what is the reason it is not working
function abc() {
var i, ele, node, parent;
var num = document.getElementById("name").value;
//num=parseInt(num);
var parent = document.getElementById("listName");
var node = document.createTextNode(num);
var ele = document.createElement("option");
ele.append(node);
parent.appendChild(ele);
//alert(num);
//num++;
document.getElementById("name").value = "";
}
<form>
<input type="input" id="name" list="listName" />
<datalist id="listName"></datalist>
<input type="submit" onclick="abc()" />
</form>
Valuing the attribute type of the input element with the submit value means submit the form.
The button documentation states indeed :
submit: The button submits the form data to the server. This is the
default if the attribute is not specified, or if the attribute is
dynamically changed to an empty or invalid value.
You don't have any form, so the current page is considered as the actual form.
As you click on the button, the function associated to onclick() is first invoked.
It adds the option in the dataList but you will never see it because the form is submitted and so you come back to the initial state of the html page.
You don't want submit a form but having a button to bind a click event to a function.
So don't use the submit type but the button type for your input :
<input type="button" value="add option" onclick="abc()" />
that matches to your requirement :
button: The button has no default behavior. It can have client-side
scripts associated with the element's events, which are triggered when
the events occur.
As a side note, your function is more complex as required and introduces too many variables that may create side effects.
This is enough :
function abc() {
var nameElement = document.getElementById("name");
var newOptionElement = document.createElement("option");
newOptionElement.textContent = nameElement.value;
var listNameElement = document.getElementById("listName");
listNameElement.appendChild(newOptionElement);
nameElement.value = "";
}
<form>
<input type="input" id="name" list="listName" />
<datalist id="listName"></datalist>
<input type="button" onclick="abc()" />
</form>
Because you used button as submit type.
If you need client side manipulation then it should not be maintain the page state (means not submit).
In your case if you will use
<input type="button" onclick="abc()" />
in place
<input type="submit" onclick="abc()" />
so it will be solve your problem.
change the html to type=button
<input type="button" onclick="abc()"/>
this works for me :
html ->
<input type="text" class='form-control' list="city" >
<datalist id="city">
</datalist>
js and jq ->
$("#city").empty(); // first empty datalist
var options=[];
options[0] = new Option('landan');
options[1] = new Option('york');
options[2] = new Option('liverPool');
$("#city").append(options);

JavaScript HTML - Extra required form fields appearing on user select

I'm trying to create a form where, if the user selects 'yes' from a dropdown, two extra fields appear. Both of these fields are required, and one of them needs to be validated according to an array of 'codes' - the user must input one of the codes in the array for the form to submit correctly. However, if the user selects 'no' from the dropdown, these fields do not appear and are not required, and the array validation does not occur and the form can be submitted.
I have some code for this, however I can't get the fields to appear. An earlier issue I encountered with this (minus the array validation - including that broke the code and stopped the extra fields appearing) was that if the user selected 'yes', and then went back to change their mind and selected 'no', then the form would not submit, clearly still requiring the fields to be filled in/correct array value inputted.
If anyone could help me in making this work I would greatly appreciate it.
HTML:
<form id="form" method="post" action="action.php">
<div class="form-group">
<label class="control-label">Defect?</label>
<select onclick='checkIfYes()' class="select form-control" id="defect" name="defect">
<option id="No" value="No">No</option>
<option id="Yes" value="Yes">Yes</option>
</select>
</div>
<div id="extra" name="extra" style="display: none">
<label class="control-label" for="desc">Description</label>
<input class="form-control" type="text" id="desc" name="desc" required disabled>
<label class="control-label" for="auth_by">Authorised By</label>
<input class="form-control" type="text" id="auth_code_input" name="auth_by" required disabled>
</div>
<hr>
<div class="form-group">
<button class="btn btn-info" id="submit" name="submit" type="submit">Submit
</button>
</div>
</form>
JavaScript:
$(document).ready(function() {
checkIfYes = function checkIfYes() {
if (document.getElementById('defect').value == 'Yes') {
// show extra fields & make them required
document.getElementById('extra').style.display = '';
document.getElementById('auth_code_input').disabled = false;
document.getElementById('desc').disabled = false;
// show user if their input is one of the codes in the array when leaving field
$('#auth_code_input').blur(function() {
if (!ValidateInput()) {
e.preventDefault();
}
});
// prevent form submission if input is not one of the codes in the array
$('#auth_form').on('submit', function(e) {
if (!ValidateInput()) {
e.preventDefault();
}
});
function ValidateInput() {
var codes = ['Foo', 'Bar']; // user must enter one of these
var IsValid = false;
var input = $('#auth_code_input').val()
if (codes.indexOf(input) > -1) { // if input equals one of the codes in the array
$('#iconBad').removeClass('glyphicon-remove').addClass('glyphicon-ok');
IsValid = true;
} else {
$('#iconBad').removeClass('glyphicon-ok').addClass('glyphicon-remove');
IsValid = false;
}
return IsValid;
}
} else { // hide and disable extra fields so form can submit
document.getElementById('extra').style.display = 'none';
document.getElementById('auth_code_input').disabled = true;
document.getElementById('desc').disabled = true;
}
}
});
JSFiddle
It's a glitch in the way you define the function -- by calling checkIfYes() it's looking for it on the global (window's) scope. By changing the line:
function checkIfYes() {...
to this:
checkIfYes = function() {...
then you've got it on the global scope. Which is, by the way, bad practice. You'd be better to create a click handler in your script itself, than to hard- code the function call in your HTML. But that's just me.
A few changes made, some pretty significant -- first, I removed the hard-coded reference to checkIfYes and simply put the event in your javascript. Second (and pretty darn significant), I moved the event handlers to the root of your javascript, rather than defining them in your checkIfYes function. This way, they don't depend on that being called each time. Try it, it works.
$(document).ready(function() {
/**
* Define some custom events to handle...
**/
$("#defect").on("change", checkIfYes );
// show user if their input is one of the codes in the array when leaving field
$('#auth_code_input').blur(function() {
if (!ValidateInput()) {
console.log("Input is wrong!");
}
});
// prevent form submission if input is not one of the codes in the array
$('#auth_form').on('submit', function(e) {
e.preventDefault();
console.log("This is where I would be checking...");
if (ValidateInput()) {
$("#auth_form").submit();
}
});
// Utility Functions.
function checkIfYes() {
if (document.getElementById('defect').value == 'Yes') {
// show extra fields & make them required
document.getElementById('extra').style.display = '';
document.getElementById('auth_code_input').disabled = false;
document.getElementById('desc').disabled = false;
} else { // hide and disable extra fields so form can submit
document.getElementById('extra').style.display = 'none';
document.getElementById('auth_code_input').disabled = true;
document.getElementById('desc').disabled = true;
}
}
function ValidateInput() {
var codes = ['Foo', 'Bar']; // user must enter one of these
var IsValid = false;
var input = $('#auth_code_input').val()
if (codes.indexOf(input) > -1) { // if input equals one of the codes in the array
$('#iconBad').removeClass('glyphicon-remove').addClass('glyphicon-ok');
IsValid = true;
} else {
$('#iconBad').removeClass('glyphicon-ok').addClass('glyphicon-remove');
IsValid = false;
}
return IsValid;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form" method="post" action="action.php">
<div class="form-group">
<label class="control-label">Defect?</label>
<select class="select form-control" id="defect" name="defect">
<option id="No" value="No">No</option>
<option id="Yes" value="Yes">Yes</option>
</select>
</div>
<div id="extra" name="extra" style="display: none">
<label class="control-label" for="desc">Description</label>
<input class="form-control" type="text" id="desc" name="desc" required disabled>
<label class="control-label" for="auth_by">Authorised By</label>
<input class="form-control" type="text" id="auth_code_input" name="auth_by" required disabled>
</div>
<hr>
<div class="form-group">
<button class="btn btn-info" id="submit" name="submit" type="submit">Submit
</button>
</div>
</form>

Simple Javascript login form

<form id="loginForm">
<p id="usernameLabel">Username:</p>
<input type="text" name="username" id="username" placeholder="username"/><br>
<p id="passwordLabel">Password: </p>
<input type="password" name="password" id="password" placeholder="password"/><br>
<input id="loginButton" type="submit" value="Login!" onsubmit="validateForm()">
</form>
<p id="loginMessage">Please Login!</p>
<script type="text/javascript">
function validateForm() {
var un = document.loginForm.username.value;
var pw = document.loginForm.password.value;
var username = "MitchWardle";
var password = "123abc456";
if ((un == username) && (pw == password)) {
window.location = "content.html";
return false;
}
else {
alert ("Login was unsuccessful, please check your username and password");
}
}
</script>
I have created a little login form on Javascript and I want it to navigate to Content.html when username and password are correct but when I click my Login button it just removes the text from the text box's, can anybody see whats wrong?
you need to return false to prevent default action of submitting the form , page gets refresh andyou loss your data, you can set type of submit button to
type="button"
or can change onsubmit to
onclick="validateForm(); return false; "
Just a couple things are off, but it's almost there:
The onsubmit handler is used at the form level. Either move the onsubmit to the <form> element or change it to an onclick event for the <input> element.
In order to reference the text fields the way you are, the <form> element also needs a name attribute. i.e. name="loginForm"
Do this:
Remove onsubmit from button add it to form.
Change id of form to name.
In the onsubmit of form append return false;.
Remove return false; from the if statements.
Change document.loginForm line to this:
document.forms['loginForm'].elements['username'].value //username/password depends.
Hope it works.
I have had the same problem as you before, and I solved it by changing the submit button to <input type="button" onclick="login();" />, and everything worked. However, the user then cannot submit the form with enter key (because there's no submit button in the form).

Categories

Resources