How get the Count of Empty Input fields? - javascript

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>

Related

how to get an array post values

In my script, I have input fields which are added dynamically. I have to get all input values using php but the problem in that $_POST['poids'] give me just the first value of input array, so just the first element of the array poids. This is my code:
$(function() {
var max_fields = 10;
var $wrapper = $(".container1");
var add_button = $(".add_form_field");
$(add_button).click(function(e) {
e.preventDefault();
const vals = $("> .item input[name^=poids]", $wrapper).map(function() {
return +this.value
}).get()
const val = vals.length === 0 ? 0 : vals.reduce((a, b) => a + b);
if ($("> .item", $wrapper).length < max_fields && val < 100) {
const $form_colis = $(".item").first().clone();
$form_colis.find("input").val("");
$wrapper.append($form_colis); //add input box
} else {
var err_msg = 'limit riched';
//alert(err_msg);
window.alert(err_msg);
}
});
$wrapper.on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
})
});
<div class="container1" style="min-height:200px">
<button class="add_form_field">Add New Field ✚</button>
<form method="post" action="postForm.php">
<div class="item">
<input type="text" placeholder="Poids" name="poids[]">
<input type="text" placeholder="Longueur" name="longueurs[]">
<input type="text" placeholder="Largeur" name="largeurs[]">
<input type="text" placeholder="Hauteur" name="hauteurs[]">
Delete
</div>
<button type="submit" name="" class="btn btn-danger btn-responsive "> Send </button></center>
</a>
</form>
</div>
to get post (postForm.php):
$poids = $_POST['poids'];
foreach($poids as $poid) {
echo " -->" .$poid;
}
I hope that you undestand what I mean.
Thank you in advance
The problem is that you're appending the div with the new input fields to $wrapper, but that's outside the form. You need to put it inside the form.
Change
$wrapper.append($form_colis); //add input box
to
$('.item', $wrapper).last().after($form_colis); //add input box
I'm no PHP expert, but by just browsing the code provided, it seems you're just searching for inputs with a name value of poids.
const vals = $("> .item input[name^=poids]",$wrapper).map(function() { return +this.value }).get()
Then when you create a bew input, you do not append poids to the input name.
const $form_colis = $(".item").first().clone();
$form_colis.find("input").val("");
$wrapper.append($form_colis);
Therefore, you will only find one with your method, and that's this one:
<input type="text" placeholder="Poids" name="poids[]">
So to solve this, inside the $form_colis method, add poids to it I do believe.

Mask the first 2 characters in input form

Hello i trying to hide/change (with *) the 1-st and 2-nt characters in input form, but value do not changed.
E.x if in my input form i put sarahlovecode in input form show **rahlovecode, but when submit get the full value sarahlovecode
HTML:
<input type="text" class="input" name="secret_word" id="secret_word">
And Js i using is:
$.fn.mask = function( regexp, matchGroup, callback ) {
this.on("blur", function(e){
$(this).data("value", this.value);
var result;
while (result = regexp.exec(this.value)) {
var matches = result.slice(1);
if (callback){
var substitute = callback(matches[0]);
} else {
var substitute = Array(matches[matchGroup-1].length + 1).join("*");
}
matches[matchGroup-1] = substitute;
this.value = matches.join("");
}
})
this.on("focus", function(e){
this.value = $(this).data("value") || "";
});
}
// With Regular expression
phoneRegexp = new RegExp("(.*?)(.{1})$", "g");
$("#secret_word").mask(phoneRegexp, 2);
ref: https://www.sitepoint.com/community/t/mask-input-fields-without-affecting-validation/37100/15
And it's working but change the value with **, same as input word.
Suggestion to fix this?
Thanks.
You need to change the value of the input back when you submit the form. Add a function on the event "onsubmit" of the form:
<form onsubmit="fix_asterisk();">
<fieldset>
<input type="text" class="input" name="secret_word" id="secret_word">
</fieldset>
<input type="submit">
</form>
Then in the javascript add the function:
<script>
function fix_asterisk(){
let input = document.getElementById("secret_word");
input.value = $(input).data("value");
}
</script>

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>

Prevent text entry in textbox unless checkbox is checked

I'm trying to prevent text from being entered in a textbox unless a checkbox that corresponds with the textbox is checked.
// Validate "Other" textbox
var isOther = document.getElementById("isOther");
isOther.addEventListener("input", function (evt) {
// Checkbox must be checked before data can be entered into textbox
if (isOther.checked) {
document.getElementById("other").disabled = false;
} else {
document.getElementById("other").disabled = true;
}
});
Do not use disabled. Instead use readonly. During document load, uncheck and disable the inputs:
<input type="checkbox" id="isOther" />
<input type="text" id="other" readonly />
And use this script.
// Validate "Other" textbox
var isOther = document.getElementById("isOther");
var other = document.getElementById("other");
isOther.addEventListener("click", function () {
other.readOnly = !isOther.checked;
});
other.addEventListener("focus", function (evt) {
// Checkbox must be checked before data can be entered into textbox
other.readOnly = !isOther.checked;
});
Longer version.
// Validate "Other" textbox
var isOther = document.getElementById("isOther");
var other = document.getElementById("other");
isOther.addEventListener("click", function () {
if (isOther.checked) {
other.readOnly = false;
} else {
other.readOnly = true;
}
});
other.addEventListener("focus", function (evt) {
// Checkbox must be checked before data can be entered into textbox
if (isOther.checked) {
this.readOnly = false;
} else {
this.readOnly = true;
}
});
Fiddle: http://jsfiddle.net/praveenscience/zQQZ9/1/
Fiddle: http://jsfiddle.net/praveenscience/zQQZ9/
My solution uses jQuery library. Here's a fiddle: http://jsfiddle.net/8LZNa/
Basically I'm disabling the input on page load:
<input name="isOther" type="checkbox" id="isOther" /><br />
<input type="text" id="other" disabled/>
... and when isOther changes it will make sure it is checked, and change the state to enabled. Or change back to disabled.
$('input[name=isOther]').change(function(){
if($(this).is(':checked')) {
$("#other").removeAttr('disabled');
}
else{
$("#other").attr('disabled','disabled');
}
});
You can do this:
document.getElementById( 'isOther' ).onChange = function(){
document.getElementById("other").disabled = !this.checked;
};
Without the use of jQuery or disabled property:
HTML
<input type="checkbox" id="x" value="Enable textbox" onclick="test(this);" />
<input type="text" id="y" readonly />
JAVASCRIPT
function test(checkbox) {
if(checkbox.checked) {
document.getElementById('y').readOnly = false;
}
else {
document.getElementById('y').readOnly = true;
}
}

adjusting default value script to work with multiple rows

I am using a default value script (jquery.defaultvalue.js) to add default text to various input fields on a form:
<script type='text/javascript'>
jQuery(function($) {
$("#name, #email, #organisation, #position").defaultvalue("Name", "Email", "Organisation", "Position");
});
</script>
The form looks like this:
<form method="post" name="booking" action="bookingengine.php">
<p><input type="text" name="name[]" id="name">
<input type="text" name="email[]" id="email">
<input type="text" name="organisation[]" id="organisation">
<input type="text" name="position[]" id="position">
<span class="remove">Remove</span></p>
<p><span class="add">Add person</span><br /><br /><input type="submit" name="submit" id="submit" value="Submit" class="submit-button" /></p>
</form>
I am also using a script so that users can dynamically add (clone) rows to the form:
<script>
$(document).ready(function() {
$(".add").click(function() {
var x = $("form > p:first-child").clone(true).insertBefore("form > p:last-child");
x.find('input').each(function() { this.value = ''; });
return false;
});
$(".remove").click(function() {
$(this).parent().remove();
});
});
</script>
So, when the page loads there is one row with the default values. The user would then start adding information to the inputs. I am wondering if there is a way of having the default values show up in subsequent rows that are added as well.
You can see the form in action here.
Thanks,
Nick
Just call .defaultValue this once the new row is created. The below assumes the format of the columns is precticable/remains the same.
$(".add").click(function() {
var x = $("form > p:first-child");
x.clone(true).insertBefore("form > p:last-child");
x.find('input:not(:submit)').defaultvalue("Name", "Email", "Organisation", "Position");
return false;
});
You should remove ids from the input fields because once these are cloned, the ids, classes, everything about the elements are cloned. So you'll basically end up with multiple elements in the DOM with the same id -- not good.
A better "set defaults"
Personally I would remove the "set defaults plugin" if it's used purely on the site for this purpose. It can easily be re-created with the below and this is more efficient because it doesn't care about ordering of input elements.
var defaults = {
'name[]': 'Name',
'email[]': 'Email',
'organisation[]': 'Organisation',
'position[]': 'Position'
};
var setDefaults = function(inputElements)
{
$(inputElements).each(function() {
var d = defaults[this.name];
if (d && d.length)
{
this.value = d;
$(this).data('isDefault', true);
}
});
};
Then you can simply do (once page is loaded):
setDefaults(jQuery('form[name=booking] input'));
And once a row is added:
$(".add").click(function() {
var x = $("form > p:first-child");
x.clone(true).insertBefore("form > p:last-child");
setDefaults(x.find('input')); // <-- let the magic begin
return false;
});
For the toggling of default values you can simply delegate events and with the help of setDefault
// Toggles
$('form[name=booking]').delegate('input', {
'focus': function() {
if ($(this).data('isDefault'))
$(this).val('').removeData('isDefault');
},
'blur': function() {
if (!this.value.length) setDefaults(this);
}
});
Fiddle: http://jsfiddle.net/garreh/zEmhS/3/ (shows correct toggling of default values)
Okey, first of all; ids must be unique so change your ids to classes if you intend to have more then one of them.
and then in your add function before your "return false":
var
inputs = x.getElementsByTagName('input'),
defaults = ["Name", "Email", "Organisation", "Position"];
for(var i in inputs){
if(typeof inputs[i] == 'object'){
$(inputs[i]).defaultvalue(defaults[i]);
}
}

Categories

Resources