Submit Form when all fields completed - javascript

I have this form
<form method="post" name="lunch" id="lunch">
<input type="number" id="people" name="people" onchange="calculo_lunch()" class="form-control">
<input type="number" id="duration" name="duration" onchange="calculo_lunch()" class="form-control">
</form>
And i use this jquery script to submit it
$(function(){
$("#lunch").submit(function(){
//jquery code
return false; // Evitar ejecutar el submit del formulario.
})
});
$('input[type="number"]').on('change', function() { $("#lunch").trigger('submit'); })
This submit my form when one of the fields is changed but now i need that this form triggers when both of the fields are completed

This will check each 'number' type input and count up the number that have some value. If the number of inputs with values matches the number of inputs, the form submits. This will work for any number of inputs, so if you add 10 more it will still work.
$('input[type="number"]').on('change', function() {
//initialize counter
var completed_fields = 0;
//count up the number of completed number inputs
$('#lunch').find('input[type="number"]').each(function(){
if($(this).val()){
completed_fields += 1;
}
});
//test the number of completed fields vs the total number of fields
if($('#lunch').find('input[type="number"]').length == completed_fields)
{
$("#lunch").trigger('submit');
}
});

Try this.
var fields = $('input[type="number"]'); //store all fields ref
fields.change(function() {
if(fields.filter(function(){
return !!$(this).val();
}).length == field.length) { //all fields has values.
$("#lunch").submit();
}
})

$(function(){
$("#lunch").submit(function(){
//check if both values are whatever you need -->
if (parseInt($('#people').val()) > 0 && parseInt($('#duration').val()) > 0){
//jquery code
}else{
return;
}
}
});
return false; // Evitar ejecutar el submit del formulario.
})
});
$('input[type="number"]').on('change', function() { $("#lunch").trigger('submit'); })

You want to make sure that each input has a value before triggering the submit event and bind your onChange event within DOM ready.
$(function(){
$("#lunch").submit(function(){
//jquery code
return false; // Evitar ejecutar el submit del formulario.
}); // end submit
$('input[type="number"]').on('change', function() {
if( $('input[type="number"]').filter(function() { return this.value == ''; }).length === 0 ) {
$("#lunch").trigger('submit');
}
});
});

You can use html5 required tag on the fields:
<input type="number" id="people" name="people" onchange="calculo_lunch()" class="form-control" required>
that should prevent submitting if field is empty..

Related

How get the Count of Empty Input fields?

How can I check the Number of Incomplete Input fields in Particular ID, (form1, form2).
If 2 input fields are empty, in i want a msg saying something like "Incomplete Input 2"
How is it Possible to do this in JS ?
<div id="form1">
<span>Number of Incomplete Input: 2</span>
<input type="text" value="">
<input type="text" value="">
</div>
<div id="form2">
<span>Number of Incomplete Input: 1</span>
<input type="text" value="Test">
<input type="text" value="">
</div>
This is the JS, which is working, i have have multiple JS with class named assigned to each inputs and get the value, but i need to make this check all the Input fields inside just the ID.
$(document).on("click", "#form1", function() {
var count = $('input').filter(function(input){
return $(this).val() == "";
}).length;
alert(count);
});
Your html structure, especially form structure is not correct, so you should first add some submit button to form that can be clicked. Then you can add event listener on form's submission. In the event handler you should select children inputs inside the form tag using $(this).children("input"). Now you can filter them.
$(document).on("submit", "#form1", function (e) {
e.preventDefault();
var count = $(this)
.children("input")
.filter(function (input) {
return $(this).val() == "";
}).length;
alert(count);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form1">
<span>Number of Incomplete Input: 2</span>
<input type="text" value="">
<input type="text" value="">
<button type="submit">Submit</button>
</form>
This is the JS, which is working, if I have have multiple JS with class named assigned to each inputs and Im getting the value, but i have multiple JS for this to work.
How can i make this Simpler say like, when user clicks on Div, it only checks the input fields inside that div.
$(document).on("click", "#form1", function() {
var count = $('.input_field1').filter(function(input){
return $(this).val() == "";
}).length;
alert(count);
});
HTML
<div id="form1">
<span>Number of Incomplete Input: 2</span>
<input type="text" value="" class="input_field1">
<input type="text" value=""class="input_field1">
</div>
<div id="form2">
<span>Number of Incomplete Input: 1</span>
<input type="text" value="Test" class="input_field2">
<input type="text" value="" class="input_field2">
</div>
See snippet below:
It has commented and if you put some effort on it, you can have a jQuery plugin out of it.
(function () {
'use strict';
var
// this use to prevent event conflict
namespace = 'customValidation',
submitResult = true;
var
input,
inputType,
inputParent,
inputNamePlaceholder,
//-----
writableInputTypes = ['text', 'password'],
checkboxInputType = 'checkbox';
var
errorContainerCls = 'error-container';
// Add this function in global scope
// Change form status with this function
function changeFormStatus(status) {
submitResult = submitResult && status;
}
// Check if a radio input in a
// group is checked
function isRadioChecked(form, name) {
if(!form || !name) return true;
var radio = $(form).find('input[type="radio"][name="' + name.toString() + '"]:checked');
return typeof radio !== 'undefined' && radio.length
? true
: false;
}
function eachInputCall(inp, isInSubmit) {
input = $(inp);
inputType = input.attr('type');
// assume that we have a name placeholder in
// attributes named data-name-placeholder
inputNamePlaceholder = input.attr('data-name-placeholder');
// if it is not present,
// we should have backup placeholder
inputNamePlaceholder = inputNamePlaceholder ? inputNamePlaceholder : 'input';
if(!inputType) return;
// you have three type of inputs in simple form
// that you can make realtime validation for them
// 1. writable inputs ✓
// 2. checkbox inputs ✓
// 3. radio inputs ✕
// for item 3 you should write
// another `else if` condition
// but you should have it for
// each name (it was easier if it was a plugin)
// radio inputs is not good for realtime
// unchecked validation.
// You can check radios through submit event
// let make it lowercase
inputType = inputType.toLowerCase();
// first check type of input
if ($.inArray(inputType, writableInputTypes) !== -1) {
if(!isInSubmit) {
input.on('input.' + namespace, function () {
writableInputChange(this);
});
} else {
writableInputChange(inp);
}
} else if ('checkbox' == inputType) { // if it is checkbox
if(!isInSubmit) {
input.on('change.' + namespace, function () {
checkboxInputChange(this);
});
} else {
checkboxInputChange(inp);
}
}
}
// Check if an input has some validation
// (here we have just required or not empty)
function writableInputChange(inp) {
// I use $(this) instead of input
// to prevent conflict if selector
// is a class for an input
if('' == $.trim($(inp).val())) {
changeFormStatus(false);
// your appropriate message
// you can use bootstrap's popover
// to modefy just input element
// and make your html structure
// more flexible
// or
// if your inputs are in
// separate containers do
// somthing like below
inputParent = $(inp).parent();
if(!inputParent.children('.' + errorContainerCls).length) {
inputParent.append($('<div class="' + errorContainerCls + '" />').text('Please fill ' + inputNamePlaceholder));
}
} else {
changeFormStatus(true);
// I assume we have separate
// containers for each input
inputParent = $(inp).parent();
inputParent.children('.' + errorContainerCls).remove();
}
}
// Check if an checkbox is checked
function checkboxInputChange(chk) {
if(!$(chk).is(':checked')) {
changeFormStatus(false);
// if your inputs are in
// separate containers do
// somthing like below
inputParent = $(chk).parent();
if(!inputParent.children('.' + errorContainerCls).length) {
inputParent.append($('<div class="' + errorContainerCls + '" />').text('Please check ' + inputNamePlaceholder));
}
} else {
changeFormStatus(true);
// I assume we have separate
// containers for each input
inputParent = $(chk).parent();
inputParent.children('.' + errorContainerCls).remove();
}
}
$(function () {
var
form = $('#form'),
// you can change this selector with your classes
formInputs = form.find('> .input-group > input');
formInputs.each(function () {
eachInputCall(this);
});
form.submit(function () {
submitResult = true;
// check all inputs after form submission
formInputs.each(function () {
eachInputCall(this, true);
});
// Because of radio grouping by name,
// we should select them separately
var selectedGender = isRadioChecked($(this), 'gender');
var parent;
if(selectedGender) {
changeFormStatus(true);
parent = $(this).find('input[type="radio"][name="gender"]').parent();
parent.children('.' + errorContainerCls).remove();
} else {
changeFormStatus(false);
// I assume that all radios are in
// a separate container
parent = $(this).find('input[type="radio"][name="gender"]').parent();
if(!parent.children('.' + errorContainerCls).length) {
parent.append($('<div class="' + errorContainerCls + '" />').text('Please check your gender'));
}
}
if(!submitResult) {
console.log('There are errors during validations!');
}
return submitResult;
});
});
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form">
<div class="input-group">
<input type="text" name="input1" data-name-placeholder="name">
</div>
<div class="input-group">
<input type="checkbox" name="input2" data-name-placeholder="agreement">
</div>
<div class="input-group">
<input type="radio" name="gender">
<input type="radio" name="gender">
</div>
<button type="submit">
submit
</button>
</form>

Jquery min and max show new page

I would like to validate myForm, so the user can input a value between 1 and a max on 99. When I submit a number I get showed a blank page, which is the select.php. But I would like to stay on my indexpage, and get the message "You are below". Can anyone see what is wrong here?
index.html:
<div class="content">
<p id="number"></p>
<div class="form">
<form id="myForm" action="select.php" method="post">
<input type="number" name="numbervalue" id="numberinput">
<input type="submit" id="sub" Value="Submit">
<span id="result"></span>
<span id="testnumber"></span>
</form>
</div>
</div>
JS:
var minNumberValue = 1;
var maxNumberValue = 99;
$('#sub').click(function(e){
e.preventDefault();
var numberValue = $('input[name=numbervalue]').val();
if(isNaN(numberValue) || numberValue == ''){
$('#testnumber').text('Please enter a number.')
return false;
}
else if(numberValue < minNumberValue){
$('#testnumber').text('You are below.')
return false;
}
else if(numberValue > maxNumberValue){
$('#testnumber').text('You are above.')
return false;
}
return true;
});
// Insert function for number
function clearInput() {
$("#myForm :input").each( function() {
$(this).val('');
});
}
$(document).ready(function(){
$("#sub").click( function(e) {
e.preventDefault(); // remove default action(submitting the form)
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info){
$("#result").html(info);
});
clearInput();
});
});
// Recieve data from database
$(document).ready(function() {
setInterval(function () {
$('.latestnumbers').load('response.php')
}, 3000);
});
How about utilizing the 'min' and 'max' attributes of the input tag, it would handle all the validation itself:
<input type="number" name="numbervalue" min="1" max="99">
Cheers,
Here's a little function to validate the number:
var minNumberValue = 1;
var maxNumberValue = 99;
$('#sub').click(function(e){
e.preventDefault();
var numberValue = $('input[name=numbervalue]').val();
if(isNaN(numberValue) || numberValue == ''){
$('#result').text('Please enter a number.')
return false;
}
else if(numberValue < minNumberValue){
$('#result').text('You are below.')
return false;
}
else if(numberValue > maxNumberValue){
$('#result').text('You are above.')
return false;
}
return true;
});
You can define the minimum and maximum values by changing the two variables (be sure to check these server-side too if you are submitting to a server, as the user could manipulate the code via dev tools to change these boundaries or submit whatever they want).
The result message is displayed in your span#result, otherwise you could use alert() too.
The important things here are the e parameter in the click function (it's the JavaScript event), calling e.preventDefault() (if you don't do this, the form will submit before finishing validation, as the default action for an input[type=submit] is to submit a form [go figure...]), returning false whenever the conditions aren't met, and returning true if it satisfies the validation. The return true; allows the form to follow its action parameter.
And a fiddle with this: https://jsfiddle.net/3tkms7vn/ (edit: forgot to mention, I commented out return true; and replaced it with a call to add a message to span#result just to prevent submission on jsfiddle.)

Check if every elemnt from a form is filled JQUERY

I have a form with all types of form elemnts and I have a code that should run through every single one of the elemnts and check their value after the submit button is clicked. Unfortunatelly, this code doesn't work completely. What I mean is that if I don't enter any value in the input, it will print the message, but if I enter some text in it, we go to the else statement, without checking the other.
Could somebody tell me why?
if($('form.registration-form :input').val() == '')
{
// Print Error Message
}
else
{
// Do something else
}
You can use filter method for this:
var emptyElements = $('form.registration-form :input').filter( function() {
return this.value === '';
});
if( emptyElements.length === 0 ) {
// all IS filled in
} else {
// all is NOT filled in
}
$('#submit').click(function(){
var emptyElements = $('form.registration-form :input').filter( function() {
return this.value === '';
});
if( emptyElements.length === 0 ) {
alert('All Filled');
} else {
alert('1 or more not filled')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" class="registration-form">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="submit" id="submit" value="Check">
</form>

Attempting to prevent submitting empty form

I have a form in my HTML document, and it only has a "text" input, and a submit button.
I also have JavaScript that checks if the field is empty and returns true or false.
JSFiddle: http://jsfiddle.net/HBZ7t/
HTML:
<form onsubmit="checkNull();" method="post">
<input type="text" id="field">
<input type="submit">
</form>
JavaScript
function checkNull() {
var field = document.getElementById("field");
if(field.value !== "") {
return true;
}
return false;
}
However, the form can be submitted even if the text field is empty... Any suggestions?
You are doing nearly everything right, you just need to return the value from the function to the handler:
<form onsubmit="return checkNull();" method="post">
// -------------^^^^^^
In JavaScript you can use double exclamation points to check for lots of non-valid settings:
function checkNull() {
var field = document.getElementById("field");
if(!!field.value) {
return true;
} else {
return false;
};
FIDDLE
JS
var form=document.getElementById("form");
form.onsubmit=function(){
var field = document.getElementById("field");
if (field.value !== "") {
return true;
}
return false;
};
HTML
<form id="form" method="post">
<input type="text" id="field">
<input type="submit">
</form>
you can use event.preventDefault() to cancel a event, see mozila doc here
Also, check the very nice jQuery submit function and samples here
Check this sample: http://jsfiddle.net/HBZ7t/5/
$( "#target" ).submit(function( event ) {
if($('#field').val()=='')
{
alert('cancel event');
event.preventDefault();
}
});

Jquery validation of input array elements manually

<input type="text" name="member_name[]" size="13" value="">
<input type="text" name="member_name[]" size="13" value="">
<input type="text" name="member_name[]" size="13" value="">
<input type="text" name="member_name[]" size="13" value="">
How do i validate these 4 fields so that they are not blank.. without using jquery validate plugin.?
You can cancel the form submission by registering a submit event handler and prevent the default behavior if one of your fields is empty:
$("form").submit(function(event) {
if ($("input:text[name='member_name\\[\\]'][value='']", this).length) {
window.alert("No member name should be empty.");
event.preventDefault();
}
});
EDIT: As naveen correctly points out, the code above would still submit the form if the fields only contain whitespace. You can use $.trim() with filter() to fix the problem:
$("form").submit(function(event) {
if ($("input:text[name='member_name\\[\\]']", this).filter(function() {
return $.trim(this.value) == "";
}).length) {
window.alert("No member name should be empty.");
event.preventDefault();
}
});
$('input:submit').click(function() {
$('form').submit(function(e) {
$("input:text[name^='member_name']").each(function() {
if (!$.trim($(this).val()).length) {
alert('Name Field should not leave empty');
return false; // or e.preventDefault();
}
});
});
});
var valid = true;
$('input').each(function(){
if($(this).val() == "") {
valid = false;
}
});
// use valid here
var invalidInputs = $('input').filter(function() {
return $(this).val() == "";
});
var valid = invalidInputs.length == 0
Not most advance, but simple & clear method.
$("form").submit(function(event) {
var inputLength = $('input[type="text"]').val().length; // check for value length
if ($('input').val().length > 0) {
// submit if input value is length > 0
alert('Form submitted.');
}
else {
// error if input value is NOT length > 0
alert('Fill the form.');
event.preventDefault();
}
});

Categories

Resources