A short way of cheking multiple blank text fields jQuery - javascript

I need to check if there are blank input text fields in my < form >. Instead of doing this multiple times
$.trim($('#myMessage').val()) == '' || $.trim($('#myage').val()) == '' .//so on...
What is the best way to check multiple blank text fields?

use:
if($('input:text[value=""]').length);

try
$("form input[type=text]").filter(function () {
return $.trim(this.value) != "";
}).length;
Note: You have to use any form id or class instead of form

Here is the code ,
// Validate form fields in Sign up form
$(".signup-form").submit(function(){
var isFormValid = true;
$(".signup-form .required input:text").each(function(){ // Note the :text
if ($.trim($(this).val()).length == 0){
$(this).parent().addClass("highlight");
isFormValid = false;
} else {
$(this).parent().removeClass("highlight");
}
});
if (!isFormValid) alert("Please fill in all the required fields (highlighted in red)");
return isFormValid;
});

Related

Customize alert/error message based on the selector which is not selected

I have three selectors and currently if anyone of them is not selected, the alert message is "Please fill in the fields".
However, I want to customize the alert.
Suppose out of 3 only 1 selector is not selected - say "dimension" than how can I amend the alert to " Please fill in the field - Two".
My current code is:
if (
checkforNullEmptySelect("group")
&& checkforNullEmptySelect("one")
&& checkforNullEmptySelect("two")
&& checkforNullEmptySelect("three")
) {
// alert("Values filled in correctly");
formValid = true
getData();
return true;
} else {
alert(alertMessageArr.correctFields);
return false;
}
I am assuming your HTML structure to be as given below:
<input id="one" type="text"/>
<input id="two" type="text"/>
<input id="three" type="text"/>
Snippet to check fields are empty or not:
if(inputOne === 0 && inputTwo === 0 && inputThree === 0){
alert("Please fill all fields");
}else{
$('input').each(function() {
if ($(this).val() != '') { //Or $(this).length > 0
alert('all inputs filled');
}
else{
alert('theres an empty input'); //alert selectors if needed
return false
}
});
}
You can concatenate the selector by using "+" operator or `` if you are using es6.
// ES5 ->
alert('Please fill out the fields - ' + selector);
//ES6 -> alert(`Please fill out the fields - ${selector}`);

How do I use javascript to prevent form submission because of empty fields?

How do I make a script in javascript to output an error and prevent form submission with empty fields in the form? Say the form name is "form" and the input name is "name". I have been having some trouble with PHP not always handling the empty fields correctly, so I would like this as a backup. Any help is appreciated, thanks.
HTML Code :-
<form name='form'>
<input type="button" onclick="runMyFunction()" value="Submit form">
</form>
Javascript Code :-
function runMyFunction()
{
if (document.getElementsByName("name")[0].value == "")
{
alert("Please enter value");
}
else
{
var form= document.getElementsByName("form")[0];
form.submit();
}
}
Claudio's answer is great. Here's a plain js option for you. Just says to do nothing if field is empty - and to submit if not.
If you need to validate more than one, just add an && operator in the if statement and add the same syntax for OtherFieldName
function checkForm(form1)
{
if (form1.elements['FieldName'].value == "")
{
alert("You didn't fill out FieldName - please do so before submitting");
return false;
}
else
{
form1.submit();
return false;
}
}
This is untested code but it demonstrates my method.
It will check any text field in 'form' for empty values, and cancel the submit action if there are any.
Of course, you will still have to check for empty fields in PHP for security reasons, but this should reduce the overhead of querying your server with empty fields.
window.onload = function (event) {
var form = document.getElementsByName('form')[0];
form.addEventListener('submit', function (event) {
var inputs = form.getElementsByTagName('input'), input, i;
for (i = 0; i < inputs.length; i += 1) {
input = inputs[i];
if (input.type === 'text' && input.value.trim() === '') {
event.preventDefault();
alert('You have empty fields remaining.');
return false;
}
}
}, false);
};
Attach an event handler to the submit event, check if a value is set (DEMO).
var form = document.getElementById('test');
if (!form.addEventListener) {
form.attachEvent("onsubmit", checkForm); //IE8 and below
}
else {
form.addEventListener("submit", checkForm, false);
}
function checkForm(e) {
if(form.elements['name'].value == "") {
e.preventDefault();
alert("Invalid name!");
}
}

Remaking jQuery form validation

I am trying to remake a jQuery script by (http://jorenrapini.com/blog/javascript/the-simple-quick-and-small-jquery-html-form-validation-solution). This script is checking if a from is filled, if not a error message will appear.
What I want to do is to only get the error message when one of two form input-fields are filled out, if none of them are then they should be ignored. The form fields are named "firstinput" and "secondinput" (you can see their id in the code).
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["firstinput", "secondinput"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#theform").submit(function(){
//Validate required fields
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});
Can anybody please help me with a solution, I would really appreciate it.
/A girl that spend a LOT of time solving this without luck :(
I would wrap your for loop in a conditional that evaluates if one or the other has a value.
if($("#field1").val() == "" && $("#field2").val() == ""){
//Ignore
}else{
//Do something
}
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["firstinput", "secondinput"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#theform").submit(function(){
//Validate required fields
if($("#firstinput").val() != "" || $("#secondinput").val() != "")
{
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});

Why do these alerts multiply?

OK, i have a couple of inputs. I have this code to validate them.
$("#form1").submit(function(){
var isFormValid = true;
$("#first_name").each(function(){
if ($.trim($(this).val()).length == 0){
isFormValid = false;
}
});
if (!isFormValid) alert("Please Enter Your First Name");
return isFormValid;
});
$("#form1").submit(function(){
var isFormValid = true;
$("#last_name").each(function(){
if ($.trim($(this).val()).length == 0){
isFormValid = false;
}
});
if (!isFormValid) alert("Please Enter Your Last Name");
return isFormValid;
});
$("#form1").submit(function(){
var isFormValid = true;
$("#dropdown").each(function(){
if ($.trim($(this).val()).length == 0){
isFormValid = false;
}
});
if (!isFormValid) alert("Please Select Your Volunteer Choice");
return isFormValid;
});
For some reason, i get a message after a message. What i was aiming for is that it only show me the next field that has not been field out, not all of them at the same time. If you have a question, please comment, it is hard to explain....do not down vote until you give me a chance to better explain.
​
Here is how to simplify your code, and make it work like intended.
First, since you use the same method to validate all the fields, wrap that in a function instead of repeating the code:
function isFieldEmpty(jQuerySelector) {
return $.trim($(jQuerySelector).val()).length == 0
}
Second, use a single submit handler to check everything, and return false if any field does not pass validation:
$("#form1").submit(function(){
if(isFieldEmpty('#first_name')) {
alert("Please Enter Your First Name");
return false;
}
if(isFieldEmpty('#last_name')) {
alert("Please Enter Your Last Name");
return false;
}
if(isFieldEmpty('#dropdown')) {
alert("Please Select Your Volunteer Choice");
return false;
}
// Will return true only if all fields passed
return true;
});
I'm not familiar with JQuery but I think what is happening is your are binding 3 functions to your form, which means they all get called
when you want to do is create 1 function validate that calls your sub validations functions.
also I would recommend you change your sub validation methods to return the message instead of a boolean, this way you can display all the errors in 1 alert.
You have multiple alerts because you bind different functions to the submit event of the form: each one checks a different field and fires an alert if the field is empty.
You need to move the three validation steps in only one function and bind that function to the submit event.
Something like:
$("#form1").submit(check);
function check() {
var isFormValid = true;
var errors = array();
$("#first_name").each(function(){
if ($.trim($(this).val()).length == 0){
isFormValid = false;
errors.push("Please Enter Your First Name");
}
});
$("#last_name").each(function(){
if ($.trim($(this).val()).length == 0){
isFormValid = false;
errors.push("Please Enter Your Last Name");
}
});
$("#dropdown").each(function(){
if ($.trim($(this).val()).length == 0){
isFormValid = false;
errors.push("Please Select Your Volunteer Choice");
}
});
if (!isFormValid) {
var errorMsg = "";
for (var i = 0; i < errors.length; i++) {
errorMsg += errors[i] + "\n";
}
alert(errorMsg);
}
}
This is because of the redundancy on your code, same function, same identifier, same logic, same event handler, useless each with an id selector.
The only thing different are the subjects. Here is my suggestion.
$("#form1").submit(function(){
var errors = [];
if($("#first_name").val().length == 0){
errors.push("Please Enter Your First Name");
}
if($("#last_name").val().length == 0){
errors.push("Please Enter Your Last Name");
}
// and so on
if(var isFormValid = errors.length > 0) {
alert('you have errors');
//errors contains all the error message if you need them
}
return isFormValid;
});

JQuery condition with blank input

I need to do multiple checks in a jquery condition ...
I am looking for something like this:
IF checkbox_A is Checked then
If input_A is empty then alert('input_A is Required')
else Add a class="continue" to the div below.
<button id="btn1">Continue</button>
Possible?
I normally wouldn't do this as you haven't even shown an attempt to write any code yourself, but I'm in a good mood.
if ($("#checkboxA").is(":checked")) {
if ($("#inputA").val() == "") {
alert("input_A is required");
}
else {
$("#btn1").addClass("continue");
}
}
$(document).ready(function() {
if($("#yourCheckBoxId").is(":checked")) {
if($("#yourInputId").val() == "") {
alert("empty");
}
else {
$("button[id='btn1']").addClass("continue");
}
}
});
yes, it's possible:
$('#checkBoxA').click(function() {
var checkBoxA = $('#checkBoxA');
var textBoxA = $('#textBoxA');
if (checkBoxA.checked())
{
if (textBoxA.val() == "")
{
$('#btn1').removeClass('continue');
alert("No value entered");
textBoxA.focus();
}
else {
$('#btn1').addClass('continue');
}
} else {
$('#btn1').addClass('continue');
}
});
Maybe
if ( document.getElementById('checkbox_A').checked ){
if (document.getElementById('input_A').value == ''){
alert('input_A is Required')
} else {
$('#btn1').addClass('continue;);
}
}
But if you have multiple elements you want to validate you can avoid manual checking of each field and automate by adding an required class to the element that are required..
<input type="text" name="...." class="required" />
now when you want to validate the form you do
// find the required elements that are empty
var fail = $('.required').filter(function(){return this.value == ''});
// if any exist
if (fail.length){
// get their names
var fieldnames = fail.map(function(){return this.name;}).get().join('\n');
// inform the user
alert('The fields \n\n' + fieldnames + '\n\n are required');
// focus on the first empty one so the user can fill it..
fail.first().focus();
}
Demo at http://jsfiddle.net/gaby/523wR/

Categories