Set flag when looping through input fields - javascript

I have a series of multiple text fields and a text area. I’m looping through the text fields and the text area and checking if there is a value. If there is not a value I set a flag that says pass=false. Otherwise I set pass=true and would like to fire a custom event if everything evaluates to true. The problem is that because one input field evaluates to true it evaluates them all to true even though two of the fields have no value in them. How would I go about doing this if I wanted it so that all fields have to be filled in but still set pass=false if one or two of them are filled in? Any help is greatly appreciated!
JS Fiddle link: http://jsfiddle.net/YyAjp/12/
HTML:
<form name="headerForm">
<label for="fname">*First Name</label>
<input type="text" class="text" id="fname" name="fname" />
<br/>
<label for="mname">*Middle Name</label>
<input type="text" class="text" id="mname" name="mname" />
<br/>
<label for="fname">*Last Name</label>
<input type="text" class="text" id="lname" name="lname" />
<br/>
<label for="notes">*Notes</label>
<textarea name="notes" /></textarea>
Submit
</form>
JQUERY
$(document).ready(function() {
$("#submit").on('click', function() {
var pass;
$("input,textarea,select").each(function() {
if($(this).val() === ''){
pass = false;
$(this).prev('label').css('color','red');
} else {
pass = true;
$(this).prev('label').css('color','black');
}
});
console.log(pass);
if(pass){ alert('trigger custom event') } else { alert('pass failed'); }
});
});

Change
pass = true;
into
pass = pass && true;
and initialize it to true:
$("#submit").on('click', function() {
var pass = true;
http://jsfiddle.net/mblase75/pgM5X/
(You might also want to use $.trim() on the values first.)

Related

Disable and enable button in js

i want to make a form with inputs and "submit" button. Idea is to disable button as long as inputs are empty or value of input not correctly (email validation).
I have my js code, but the problem is that, button starts at the beggining as disabled, but when i write something in first input it start to be not disabled, even if rest of inputs have not correct value.
My function:
document.getElementById("my-button").disabled = true
function inputValidator() {
var $element = $(this);
// for all input fields
if ($element.val()) {
$element.closest('.my-form__item').removeClass('error');
document.getElementById("my-button").disabled = false;
} else {
$element.closest('.my-form__item').addClass('error');
document.getElementById("my-button").disabled = true;
}
// for email field
if ($element.attr('id') === 'email' && $element.val()) {
if (!reg.test($element.val())) {
$element.closest('.my-form__item').addClass('error');
document.getElementById("my-button").disabled = true;
} else {
$element.closest('.my-form__item').removeClass('error');
document.getElementById("my-button").disabled = false;
}
}
Does anyone knows how to solve it?
Iterate over each element inside the form and check if one elements value length is zero. Note: Also the submit button needs a value in this implementation. A more native way would be to simply add the required tag to each input which also gives a good user experience.
JS approach
function validateForm() {
let inputs = document.forms["example"].elements;
let status = true;
[...inputs].forEach((input) => {
if(input.value.length == 0) status = false;
});
document.getElementById('submit').disabled = !status;
}
<form id="example">
<p>
<label>First name</label><br>
<input type="text" name="first_name" onKeyup="validateForm()">
</p>
<p>
<label>Last name</label><br>
<input type="text" name="last_name" onKeyup="validateForm()">
</p>
<p>
<label>Email</label><br>
<input type="email" name="email" onKeyup="validateForm()">
</p>
<p>
<button disabled=true id="submit" value="submit">Submit</button>
</p>
</form>
Pure HTML Approach
<form id="example">
<p>
<label>First name</label><br>
<input type="text" name="first_name" required>
</p>
<p>
<label>Last name</label><br>
<input type="text" name="last_name" required>
</p>
<p>
<label>Email</label><br>
<input type="email" name="email" required>
</p>
<p>
<input type="submit" value="Submit">
</p>
</form>

`Required` attribute not working with <form> tag [duplicate]

This question already has answers here:
HTML5 required attribute not working
(2 answers)
Closed last month.
My required attribute doesn't specify that an input field must be filled out before submitting the form.
HTML:
<!-- Modal Content -->
<form class="modal-content2">
<div class="container3">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="firstName"><b>First Name</b></label>
<input type="text" id="firstName" placeholder="Enter First Name" name="firstName" required>
<label for="lastName"><b>Last Name</b></label>
<input type="text" id="lastName" placeholder="Enter Last Name" name="lastName" required>
<label for="username"><b>Username</b></label>
<input type="text" id="username" placeholder="Enter Username" name="username" required>
<label for="email"><b>Email</b></label>
<input type="text" id="email" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" id="password" placeholder="Enter Password" name="psw" onfocus="this.value=''"
required>
<label for="psw-confirm"><b>Confirm Password</b></label>
<input type="password" id="cfmpassword" placeholder="Confirm Password" name="psw-confirm" onfocus="this.value=''"
required>
<br>
<br>
<p>By creating an account you agree to our <a href="aboutus.html" style="color:dodgerblue">Terms &
Privacy</a>.</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('id02').style.display='none'" class="cancelbtn2">Cancel</button>
<button type="button" class="signupbtn" onclick="signUp()">Sign Up</button>
</div>
</div>
</form>
JavaScript:
function signUp() {
if (document.getElementById("password").value == document.getElementById("cfmpassword").value) {
var users = new Object();
users.firstName = document.getElementById("firstName").value;
users.lastName = document.getElementById("lastName").value;
users.username = document.getElementById("username").value;
users.email = document.getElementById("email").value;
users.password = document.getElementById("password").value;
var postUser = new XMLHttpRequest(); // new HttpRequest instance to send user details
postUser.open("POST", "/users", true);
postUser.setRequestHeader("Content-Type", "application/json");
postUser.send(JSON.stringify(users));
//go to the logged in page
window.location = "main.html";
}
else {
alert("Password column and Confirm Password column doesn't match!")
}
}
As the required attribute does not work, users can continuously submit empty forms and those will be stored in my SQL database
I don't have a <button type="submit"> in the form as this prevents me from using windows.location.
I am new to programming, can someone please give some suggestions (with explanations) on what to do to fix this? Any help would be appreciated! Thanks a lot! (I am using vanilla JavaScript for this)
The required attribute does not work because your form is not submitted. You need to specify a button with a type="submit" or <input type="submit"> to submit your form.
I suggest you to move the signUp function inside the form tag like this with an onsubmit event:
<form onsubmit="signUp(event)">.
Then add this to you Javascript function:
function signUp(event) {
event.preventDefault();
... your old code
}
For me, I see a number of possible issues. I have tried to remove them with the following sample code. I am assuming that /users will return something useful for checking and alerting the member if there is an error with the accessing of /users or the processing of the data.
The use of the required attribute of <input> will do nothing obvious in your code as the <button> has an onclick=signUp() call which will triggered before the browser check. With your current code the form values (present or not) will still be sent to /users as there is no testing for those values.
You need to move the signUp() call to the <form> if you want the browser check to be run.
To test this, removing the onclick=signUp() in the <button> will show you a browser tip window saying the value is needed.
As you are insisting on using AJAX to post the form data, moving the check to the <form> submit is idea and personally, I would still be checking the values - just good practice.
The next issue is you are not waiting for the return of a success or fail response from /users. In fact, you are blindly redirecting to main.html. If there is an error, the user will never know. This is a very bad user experience.
This is corrected in the sample code by checking for a response with a call-back, checking that response value and then alerting the member or redirecting if there is no error.
var users = {};
function ajaxPost(url,postData,callFunc) {
var http = new XMLHttpRequest();
if(! http){
return false;
}
http.onreadystatechange=function(){
if((http.readyState == 4) && (http.status == 200)) {
if(callFunc){
callFunc(http.responseText);
}
}
}
http.open('POST',url,true);
http.send(postData);
}
function validResult(str) {
if (str == "valid") {
// go to the logged in page
window.location = "main.html";
} else {
console.log("invalid result, let the user know");
}
}
function signUp(e) {
if(e){e.stopPropagation();e.preventDefault();}
var d = document.getElementById("signupForm").querySelectorAll("input");
var i, max = d.length;
// Quick check for values only. No check for the format of the values.
// This is good practice as a browser may still ignore the `required`
// attribute.
for(i=0;i<max;i++) {
d[i].value = d[i].value.trim();
if (d[i].value) {
users[d[i].name] = d[i].value;
} else {
// An alert would be better for the user here.
console.log("Missing value for ["+ d[i].name +"]");
// Go no further if there is a missing value.
return;
}
}
// at this point, all values added to the users object.
console.log("users:["+ JSON.stringify(users) +"]");
// Send the data and wait for a return value from /users
// --- remove comment on the following line to post ----
//ajaxPost("/users",JSON.stringify(users),validResult);
}
window.onload = function(){
var c = document.getElementById("signupForm");
if (c) {
c.addEventListener("submit",signUp,false);
}
}
<form id="signupForm">
<label for="firstName"><b>First Name</b></label>
<input type="text" id="firstName" placeholder="Enter First Name" name="firstName" required>
<p>
<label for="email"><b>Email</b></label>
<input type="email" id="email" placeholder="Enter Email" name="email" required>
<p>
<button id="submit" type="submit">Check and submit</button>
</form>
Basic of HTML5 validation. You have it on button click and that runs before the validation happens. This shows you that the onclick runs and the onsubmit does not. Use the correct event.
function loginSubmit () {
console.log('loginSubmit')
}
function loginClick () {
console.log('loginClick')
}
<form onsubmit="loginSubmit()">
<input name="foo" required />
<button onclick="loginClick()">click</button>
</form>
The way required attribute works is it determines whether the element its assigned to has a value length higher than a zero, if that statement is false (meaning the value length of zero) then upon submitting the form it focuses that element as its "required" to be fulfilled.
Here is an example with JavaScript and how checking input fields could work inside it.
const form = document.querySelector('form[action="signup.php"]'); // Form
const inputs = form.querySelectorAll('input'); // All input elements inside the form
const submit = form.querySelector('button[type="submit"]'); // Submit button inside the form
// Add onclick event to the form button
submit.addEventListener('click', function(event) {
event.preventDefault(); // This prevents the button from submitting the form the traditional way
submit_form(); // but instead our way
});
function submit_form()
{
// We iterate through the form input elements
for (var i = 0; i < inputs.length; i++)
{
// We check if the current element has
// the attribute required and if so
// we proceed with checks
if (inputs[i].hasAttribute('required') && inputs[i].value.length == 0)
{
inputs[i].focus(); // We focus on the required element
alert(inputs[i].placeholder+' is required!'); // Alert the user that the element is required
break; // Break from the loop
}
else
{
if (i == (inputs.length - 1)) form.submit(); // If the loop's i variable counter hits the same value as the
// input elements length then it means all fields are filled
}
}
}
form {
width:300px;
margin:auto
}
form button,
form input {
width:100%;
height:48px;
padding:0 15px;
font-size:18px;
box-sizing:border-box;
}
form input:focus {
background-color:#f2dfb7;
}
<form action="signup.php" method="POST">
<input type="text" name="first_name" placeholder="First Name" required>
<input type="text" name="last_name" placeholder="Last Name" required>
<input type="email" name="email" placeholder="Email Address" required>
<input type="email" name="email_repeat" placeholder="Email Address (Repeat)" required>
<input type="password" name="password" placeholder="Password" required>
<input type="text" name="phone" placeholder="Phone Number" required>
<input type="text" name="birthday" placeholder="Birthday (MM/DD/YYYY)" required>
<button type="submit">Sign Up</button>
</form>

How to make pop up show up after the fields of the form are fulfilled?

I'm making a website for a project and I've added a subscribe to our newsletter section and I've set up a pop when you click the subscribe button. Before I added that js, the form wouldn't proceed until both fields were filled out and it showed a popup telling you to fill it.
<input type="text" placeholder="Name" name="name" required>
<input type="text" placeholder="Email address" name="mail" required>
<label>
<input type="checkbox" checked="checked" name="subscribe"> Daily
Newsletter
</label>
<input type="submit" value="Subscribe" onclick="myFunction1()">
Now with the js, it shows the pop up I made thanking the person for subscribing when I click the subscribe button regardless if the fields are filled or not.
function myFunction1() {
alert("Thanks for subscribing!")
}
You should include all the inputs in a form tag, as so:
<form id='myForm'>
<input type="text" placeholder="Name" name="name" required>
<input type="text" placeholder="Email address" name="mail" required>
<label>
<input type="checkbox" checked="checked" name="subscribe"> Daily
Newsletter
</label>
<input type="submit" value="Subscribe" onclick="myFunction1()">
</form>
This approach is better because then all the inputs are together in one entity, without it the 'submit' input won't really work. It won't know what is being submitted. Within the form tag it knows it's submitting the form together with all inputs contained within.
The form tag has its own set of events that you can add listeners to.
Including a 'submit' event.
To add the event listener to run your function whenever a submit happens on the form, you can do as so:
document.getElementById('myForm').addEventListener('submit', myFunction1)
Alternatively, you can also set the listener on the html:
<form onsubmit='myFunction1()'>
But keep in mind that with the 'addEventListener' method you can add multiple listeners to the same event. While the onsubmit property only accepts one function.
More info on events and on the addEventListener method:
https://developer.mozilla.org/en-US/docs/Web/Events
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
inside the function check for the field values. Confirm whether the fields are empty. If not then show the alert
function myFunction1() {
var f1 = ; // get value of field1;
var f2 = ; // get value of field2;
if (f1 != '' && f2 != ''){
alert("Thanks for subscribing!");
}
}
give all inputs of class, eg: 'myInput', and loop over them to check their value before alerting.
function myFunction1() {
var inputs = Array.fom(document.getElementsByClassName('myInput'));
var allChecked = false;
inputs.map(function(input){
if (input.value == '') { allChecked = false }
});
if (allChecked) { alert("Thanks for subscribing!") }
};

how to check all fields are empty in angularjs

How to check all fields in the submit form ng-submit="submit(field)" is empty in controller.js? They consists of few textboxes and one select field.
I would want an alert box to occur if all fields are empty and select option is not selected, instead of individual validation.
Thanks
While it's not exactly what you're asking about, may be $pristine is what you want? It's a flag on the form indicating whether the form has ever been edited. If someone typed and then cleared out a field, $pristine would still be false, however.
<form name="myform" ng-submit="doSubmit()" ng-controller="FormController">
<input ng-model="firstName" name="firstName" />
</form>
Then in your controller
.controller('FormController', function($scope){
$scope.doSubmit = function(){
if($scope.myform.$pristine){}
}
})
Alternatively, you can set all your fields to required="true" and use the $valid flag on the form in the same way as described above.
You can use this:
ng-show="!yourfield.length"
Something like this:
<form name="yourform">
<input name="yourfield" ng-model="somefield" ng-minlength="10" required>
<span ng-show="!yourfield.myfield.$error.required">Something</span>
</form>
You should look for Form Validation . Take a look at this tutorial.
<input name="name" class="form-control"
ng-model="user.name" placeholder="Name" required>
<div class="alert alert-danger"
ng-show="userForm.name.$error.required">
Please enter the name.
</div>
The following will show an alert if all fields are empty
angular.module('app', [])
.controller('FormController', function($scope) {
$scope.doSubmit = function(){
if (formIsEmpty($scope.myform)){
alert('You forgot to enter something before submitting');
}
};
function formIsEmpty(form) {
for (var prop in form) {
if (!form.hasOwnProperty(prop)) { continue; }
if (prop[0] === '$') { continue; }
if ($scope[prop]) { return false; }
}
return true;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<form name="myform" ng-submit="doSubmit()" ng-controller="FormController">
<input ng-model="firstName" name="firstName" />
<input ng-model="lastName" name="lastName" />
<textarea ng-model="description" name="description"></textarea>
<button type="submit">Submit</button>
</form>
</div>

How to add class to (or change class of) a form field if it is empty? jQuery

I have a form like below;
<form id="myform" name="myform">
<input type="text" class="required" value="" name="qwer" /><br />
<input type="text" value="" name="asdf" /><br />
<input type="text" class="required" value="" name="zxcv" /><br />
<input type="text" value="" name="tyui" /><br />
<input type="text" class="required" value="" name="ghjk" /><br />
<input type="submit" value="Submit" />
</form>
I want to check if the text fields with class="required" is blank or not at the time of submission. If they are blank, I want to change the corresponding blank field's class to error. If all the required fields are not empty, I want to alert the serialized data. I've tried this;
$('#myform input[type=submit]').click(function(e){
e.preventDefault();
var data = $('#myform').serialize();
if($.trim($('#myform input[type=text].required').val()).length == 0){
$(this).addClass("error");
}else{
alert(data);
}
});
How can I do this? Here is the fiddle.
You should loop over every element with the required class.
You are setting the error class on the submit button because you use $(this).addClass(), the $(this) is a reference to the submit button.
$('#myform input[type=submit]').click(function(e){
e.preventDefault();
var data = $('#myform').serialize();
[].slice.call($('#myform input[type=text].required')).forEach(function (elem, index) {
$elem = $(elem);
if($elem.val().length == 0)
$elem.addClass("error");
});
});
Fiddle demo
Fyi: HTML5 comes with a bunch of pseudo-classes to check for invalid form inputs so you don't have to code it by yourself, take a look here if you're interested.
After removing the unnecessary value="" on inputs
You can do this:
$('#myform input[type=submit]').click(function (e) {
e.preventDefault();
var data = $('#myform').serialize();
if ($('.required').is('[value=""]')) {
$('.required[value=""]').addClass("error");
} else {
alert(data);
}
});
Demo

Categories

Resources