JavaScript many input control null or not - javascript

I have 350 text inputs in the form. I want to control those for empty or not. I know for one input eg:
var ism=document.getElementById('inputtext').value;
if(ism.length==0){
return false;
}
But I have inputs :
<input type="text" name="inputtext[]"/>
What I do ?

You may want to consider the HTML 5 way; adding the required attribute to prevent form submission with empty inputs
<input type="text" required />
Trying to submit without putting anything in this will cause a message to be shown and submission prevented
Any method you choose should still have server-side validation

You check all of them I suppose ?
var inputs = document.querySelectorAll('[name="inputtext[]"]'),
isEmpty = false;
for (var i=inputs.length; i--;) {
if ( inputs[i].value.length === 0 ) {
isEmpty = true;
break;
}
}

Related

Make sure I'm selecting and running through all elements for an "each" statment

I'm trying to create a script that keeps our main button disabled until specific field requriments are met.
jQuery(document).ready(function() {//check if all are filled else disable submit
var inputFields = jQuery('#list-item-cc input, #field_28_50 input,#field_28_18 input');
inputFields.keyup(function() {
var empty = false;
inputFields.each(function() {
if (jQuery(this).val().length == 0) {
empty = true;
}
});
if (empty) {
jQuery('#gform_submit_button_28').attr('disabled', 'disabled');
} else {
jQuery('#gform_submit_button_28').removeAttr('disabled');
}
I'm having trouble thinking of a way to ensure my inputFields variable can be passed to my inputFields.each(function() in a way that would allow the loop.
We're not worried about all input fields. Just the specific inputs in our inputFields variable.
Is this an effective way to ensure a button is disabled if certain fields are not filled out and can I create the selector in the way that i did and use that in an each statement?
Looks like you are using gravity forms? In that case I would add a css class to each field that you want to validate. That way you don't have to go searching for ID's and change the code for multiple forms.
https://docs.gravityforms.com/css-ready-classes/
Here is a fiddle in which I pretend that I added "ensure-filled" to each item in the gravity forms builder
https://jsfiddle.net/dokLz4hm/3/
Also note that I added a .trim() to the value so that blank spaces aren't counted as input and made the submit button generic so it would work with any field in a form that contains the ensure-filled class
Html
<div>
<div id="arbitraty_id_1">
<input type="text" class="ensure-filled" />
</div>
<div id="arbitraty_id_2">
<input type="text" class="ensure-filled" />
</div>
<div id="arbitraty_id_3">
<input type="text" class="ensure-filled" />
</div>
<input type="submit" value="submit" disabled>
</div>
JS
$(document).ready(function() {
var inputFields = $('.ensure-filled');
inputFields.keyup(function() {
var empty = false;
inputFields.each(function() {
if ($(this).val().trim().length == 0) {
empty = true;
}
});
$('input[type="submit"]').attr('disabled', empty);
})
})

JS->Form validation on inputs. Using for loop to get all the inputs index

I have a form with 4 inputs and I want to show an alert on submit. What I have done is that I have already created the warnings that goes under every input with display:none; in CSS.
After this I have created a for loop in JS to get the index of every input and apply my if statement of showing the the alert if === null || === ""
using a variable to make the querySelector("THE CLASS").style.display="block";
Also on my form I have this line
<form method="post" class="q-form" name="form" onsubmit="return validate()">
My problem is when I submit my form the only alert that is shown is the one under the Username and after it appears it also disappears because I think that the for loop goes to the next input.
Let me know if there is something more to clarify.
Here you have all the code: https://jsbin.com/kazopahuga/1/edit?html,js,output
If you want to see the alert showing press Run with JS
Thank You!
I suggest a few modifications to your validare() function:
Add a flag indicating whether the whole form is valid, assume it's true until you find an input that is invalid. Return the value of this flag.
var isValid = true;
Capture your validation messages too so you can access them by index like your inputs:
messages = document.getElementsByClassName(' alert alert-danger custom');
When you find an invalid input, display the associated message and update the valid flag to false.
if (currentInputValue == null || currentInputValue === "") {
messages[index].style.display = "block";
isValid = false;
}
Here is the updated function:
function validare() {
var inputs, messages, index;
var isValid = true;
inputs = document.getElementsByTagName('input');
messages = document.getElementsByClassName(' alert alert-danger custom');
for (index = 0; index < inputs.length; ++index) {
var currentInputValue = inputs[index].value;
if (currentInputValue == null || currentInputValue === "") {
messages[index].style.display = "block";
isValid = false;
}
}
return isValid;
}
Updated jsbin here
Here is an updated solution: jsbin
You used querySelector which return only the first element it finds with the same class, you should have used querySelectorAll which return all the selectors.

How to put max length on a field using JavaScript?

I've got a working function for empty fields already. Do I need another function to set a max length on these fields or can I edit my current function?
If so how would I fit the max length code in?
Don't use JavaScript to do HTML's job.
<input type="text" name="fname" required maxlength="10" />
To answer your question, you need another function for the max-length. I assume your validateForm method is called at the time of submitting the form. The max-length should be set before submitting the form, preferably when the page loads. As already stated in the comments, setting max-length via the HTML attribute will be the easiest way to do this. Otherwise you need to run a javascript function when the DOM has loaded that basically sets the maxlength attribute for each element, like a.setAttribute('maxlength', '10').
Here is a functional and prettier way to check for all fields. It assumes all field have the same validity requirement.
var maxLength = 8; // or whatever you want
var fieldNames = ["fname","sname","houseno", "ad1", "city", "postcode", "mobno"];
var invalidFields = fieldNames.find(function(fieldName) {
var val = document.getElementById(fieldName).value;
return val == null || val.length == 0 || val.length > maxLength;
});
if (invalidFields.length) {
alert("Please fill ALL Required Fields (no more than " + maxLength + " chars)");
return false;
} else {
return true;
}

Enable submit when all form items are valid

I need some help with something... say I have the following form...
<form name="" id="" method="" action="">
<input type="text" id="text1" name="text1" />
<br />
<br />
<input type="text" id="text2" name="text2" />
<br />
<br />
<input type="text" id="text3" name="text3" />
<br />
<br />
<input type="text" id="text4" name="text4" />
<br />
<br />
<input type="submit" value="let's go" disabled="disabled" />
</form>
Now I want to have a simple script to enable the submit when the values of the text boxes are not an empty string or null...
So I have something like this.. which I will bind to the window.onload
function enableButton(){
var formitemsArray = ['text1','text2','text3','text4'],
i;
// Loop through all items
for(i=0;i<formitemsArray.length;i++){
// validate the length on the keypress...
formitemsArray.onkeypress = function(){
// loop through all the items again
for(j=0;j<formitemsArray.length;j++){
if(formitemsArray[j] == "" || formitemsArray[j] == null ){
// return false or something???
}else{
document.getElementById("submitButton").disabled = false;
}
}
}
}
}
Now I think I'm on the right lines to a solution but I'm getting lost when trying to make sure that all the items are greater than a zero length string as I'm returning false too soon. Can someone set me straight please?
Welcome to event bubbling!
This does the following: listen to an event (onkeypress) on the whole element and all its children! Which means you can do the following:
document.getElementById('form-id').onkeypress = function(e) {
var text1 = document.getElementById('text1'),
text2 = document.getElementById('text2'),
text3 = document.getElementById('text3'),
text4 = document.getElementById('text4')
if (text1.value.length > 0 &&
text2.value.length > 0 &&
text3.value.length > 0 &&
text4.value.length > 0) {
document.getElementById('submit-button').disabled = false
}
// As an aside, for later: if you want to get the element
// that triggered the event, you have to do the following
// to be cross-browser:
var evt = e || window.event, // IE doesn't get the event passed by argument
target = e.target || e.srcElement // 'target' is official, old versions of FF used 'srcElement'
// With the 'target' variable, you can now play.
}
There is another more generic solution, but it might not fit your needs (note that it requires a forEach shim:
// Declare a counter variable
var count = 0
document.getElementById('form-id').onkeypress = function(e) {
// Get all the inputs!
var inputs = this.getElementsByTagName('input')
// Now loop through all those inputs
// Since a NodeList doesn't have the forEach method, let's borrow it from an array!
[].forEach.call(inputs, loopThroughInputs)
}
function loopThroughInputs(input) {
// First check the type of the input
if (input.type === 'text') {
// If the value is correct, increase the counter
if (input.value.length > 0) {
count++
}
// If the 4 inputs have increased the counter, it's alright!
if (count === 4) {
document.getElementById('submit-button').disabled = false
}
}
}
And now this code was proposed by #Esailija, and it is way better and cleaner. However, it also requires ES5-Shim (for the every method):
document.getElementById('form-id').onkeypress = function(e) {
var inputs = [].slice.call( this.querySelectorAll( '[type=text]') );
document.getElementById('submit-button').disabled = !inputs.every(function(input){
return !!input.value;
});
}
(This guy is brillant, just don't tell him)
There are a few ways you can do this... One would be to keep the button enabled but use javascript to check the validity of the form data upon submission. The benefit to this is that the validation code is only run once, when the user clicks submit and is expecting his data to be validated (at least I do) .
function validateForm() {
var formElement = document.forms[0]; // you didn't give me a name
for(var i = 0, l = formElement.elements.length; i < l; i++ ) {
if( formElement.elements[i].value.length === 0 ) {
return false;
}
return true;
}
}
The other way is live validation, which would validate each input onBlur (focus lost). This method has the benefit of showing the user in real time what values are bad, however this can be very resource heavy depending on the number of form elements and the way you introduce the check.
Personally I would go with my first suggestion; however with that said if you choose to validate each element, I would do so like this:
var formElement = document.forms[0]; // you didn't give me a name
for(var i = 0, l = formElement.elements.length; i < l; i++ ) {
formElement.elements[i].addEventListener('blur', function() {
if( this.value.length === 0 ) {
alert('this input is invalid');
}
}, false);
}
The latter method also requires you hold onto a 'state' variable to determine whether or not the form is valid upon submission, or check all the values again.
Hope this sheds some light, and I hope my code examples help some.
If possible use jquery validation plugin instead of re-inventing the code, http://docs.jquery.com/Plugins/Validation its so easy to use.
In this jsfiddle you'll find a way to monitor the progress of form contents. If all the field conditions are fulfilled, a submit button is shown. Maybe it's useful for you. Bare in mind that client side checking of a form may be tampered with, so you always need a server side check too, if your data need to adhere to certain requirements. In other words: client side form checks are merely usability enhancements.

Alert if form is empty

How do I check if the whole form is empty and alert it? The form should be able to send even if there's a few empty inputs.
Edit:
Maybe I should've said that it's suppose to be JavaScript or jQuery.
And a better description:
I've got a form with one part that contains 10 input fields, you only have to fill out one.
The other part you only have to fill out name and phone or email but it's 4 fields you could fill with info.
And at last a checkbox making sure the user knows he or she didn't fill out the whole form.
I know how to check all fields and alert if one is empty. But what I don't know is how to check if the whole form is empty and alert it.
Here is quick and dirty way using pure JavaScript:
function checkForm​(oForm) {
for (var i = 0; i < oForm.elements.length; i++) {
if (GetElementValue(oForm.elements[i]).length > 0)
return true;
}
alert("all empty");
return false;
}
function GetElementValue(element) {
if ((element.type === "checkbox" || element.type === "radio") && element.checked === false)
return "";
return element.value;
}
​Live test case.
create a validate method like this in JS (extend the Switch for other form Elements like radio or checkbox inputs):
function validateForm(domForm) {
var elements = domForm.elements;
var hasData = false;
var isAEmptyString = function(string) {
if(string) {
return string.length() == 0;
}
return true;
};
for(var i = 0; i < elements.length; i++) {
var element = elements[i];
switch(element.tagName.toLowerCase()) {
case 'textarea':
if(!isAEmptyString(element.innerHTML)) {
return true;
}
break;
case 'input':
if(!isAEmptyString(element.value)) {
return true;
}
break;
case 'select':
if(element.selectedIndex >= 0) {
return true;
}
break;
}
}
return false;
};
you can call it in your form onSubmit handler
<form onsubmit="return validateForm(this);">
<textarea name="a"></textarea>
<input type="text" name="b"></input>
<select name="c">
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
</select>
<input type="submit" />
</form>
I know how to check all fields and alert if one is empty. But what I don't know is how to check if the whole form is empty and alert it.
If that is the case just put a boolean check in your code
var haveAnyErrorsTriggered = false;
// loop through fields and if any are empty change the haveAnyErrorsTriggered to true
// then
if(haveAnyErrorsTriggered){alert("One or more fields are empty.");}
if you want to check if the whole form is empty, just do the opposite
var isAtLeastOneFieldFull = false;
// loop through fields and if any are not empty change the isAtLeastOneFieldFull to true
// then
if(!isAtLeastOneFieldFull){alert("all the fields are empty");}
You are talking about Javascript form validation. Create a Javascript function (called say validateForm) that validates the fields in your form, and pops up an alert if it detects an error. It should return true if the form is to be submitted, and false if there is an error. Then in the your HTML form tag, add the clause onsubmit="return validateForm()", where validateForm is the name of your function.
Maybe the form fields listener example I once cooked in this jsfiddle can help you further? Note that client side validation will never be enough. Anyone can tamper with the javascript in your page, so you allways have to validate a form server side too.

Categories