dynamically add, validate and remove sets of form fields - javascript

I'd like to create a webpage where the user can add and remove sets of form fields by means of one add button and remove buttons related to the set to be removed. Entered values will be checked by means jquery validate, for which rules are added dynamically as well. pls see an an simplified example below of my targeted form:
What is a good structure of javascript code for adding, removing and validate sets of forms fields? I googled -also on this site- and there are many javascript examples for adding sets of formfields. I like the example I found at view-source:http://www.coldfusionjedi.com/demos/jqueryvalidation/testadd.cfm, which uses a form template. But I struggle in particular with the javascript coding for the removing buttons..(which are not in the example)
my targeted (simplified) form (template with 1 set of 3 formfields):
<form name="myForm" id="myForm" method="post" action="">
<input id="name1" name="name1" />
<input id="email1" name="email1" />
<input id="phone1" name="phone1" />
<input type="submit" value="Save">
</form>

I think that you should template the form. I.e. wrap it in a function, so you can create it again and again. Here is a jsfiddle http://jsfiddle.net/krasimir/2sZsx/4/
HTML
<div id="wrapper"></div>
add form
JS
var wrapper = $("#wrapper");
var addForm = $("#add-form");
var index = 0;
var getForm = function(index, action) {
return $('\
<form name="myForm" id="myForm" method="post" action="' + action + '">\
<input id="name' + index + '" name="name' + index + '" />\
<input id="email' + index + '" name="email' + index + '" />\
<input id="phone' + index + '" name="phone' + index + '" />\
<input type="submit" value="Save">\
remove form\
</form>\
');
}
addForm.on("click", function() {
var form = getForm(++index);
form.find(".remove").on("click", function() {
$(this).parent().remove();
});
wrapper.append(form);
});

Simple validation can be done when your form is submitted, thus:
$('#myForm').submit({
var n1 = $('#name1').val();
var e1 = $('#email1').val();
var p1 = $('#phone1').val();
if (n1=='' || e1=='' || p1=='') {
alert('Please complete all fields');
return false;
}
});
Note that the return false will abort the submit and return user to the document.
Great code for adding/removing form fields can be found in this question: https://stackoverflow.com/questions/18520384/removing-dynamically-generated-textboxes-in-jquery
jsFiddle here

If you are using KeenThemes (maybe Metronic theme)
https://preview.keenthemes.com/good/documentation/forms/formvalidation/advanced.html
You can do like this.
var form = document.getElementById('form_id');
var validator = FormValidation.formValidation(
form,
{
fields: {
name: {
validators: {
notEmpty: {
message: 'Please enter template name'
},
stringLength: {
min: 3,
trim: true,
message: 'Please enter a longer name.'
},
}
},
...
more fields here
...
},
plugins: {
trigger: new FormValidation.plugins.Trigger(),
bootstrap: new FormValidation.plugins.Bootstrap(),
},
});
function addNewFieldDynamically() {
// add new field here
...
validator.addField('field_name', {
validators : {...}
})
}
function removeFieldDynamically() {
// remove a field here
...
validator.removeField('field_name')
}

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 remove class from previous data entry into form

Note: this is a jQuery coding exercise and I am not allowed to use plugins or other modules.
I have a simple form validation script. When the user enters in data and it's empty the appropriate error gets displayed.
When the user types in the required field and submits the form again I want the error message to disappear if it's no longer empty and show the appropriate error if other fields are still empty.
I tried the following and the errors still show after entering the required form fields and a resubmission is done.
jsfiddle
HTML
<form id="myForm">
<input type="text" placeholder="Email" id="email" name="email">
<span class="error">Email not entered</span><br />
<input type="password" placeholder="Password" id="pword" name="pword">
<span class="error">Password not entered</span><br />
<input type="text" placeholder="First Name" id="fname" name="fname">
<span class="error">First Name not entered</span><br />
<input type="text" placeholder="Last Name" id="lname" name="lname">
<span class="error">Last Name not entered</span><br />
<input type="submit" value="Submit">
</form>
CSS
.error {
display: none;
}
.error_show {
display: inline-block;
color: red;
margin-bottom: 1em;
}
jQuery
// jQuery form validation
$(document).ready(function(){
// remove class from previous data entry
$('#myform span').removeClass('error_show');
// field mapping
var form_fields = {
'email' : 'email',
'pword' : 'password',
'fname' : 'first name',
'lname' : 'last name'
};
// ajax data
var data = {};
// make sure form fields were entered
$('#myForm').on('submit', function(e){
for (var field in form_fields) {
if (!$('#' + field).val()) {
$('#' + field).next().addClass('error_show');
} else if ($('#' + field).val()) {
data[field] = $('#' + field).val();
}
}
return false;
});
});
Just add removeClass() to the else branch of your validation function:
// jquery form validation
$(document).ready(function(){
// remove class from previous data entry
$('#myform span').removeClass('error_show');
// field mapping
var form_fields = {
'email' : 'email',
'pword' : 'password',
'fname' : 'first name',
'lname' : 'last name'
};
// ajax data
var data = {};
// make sure form fields were entered
$('#myForm').on('submit', function(e){
for (var field in form_fields) {
if (!$('#' + field).val()) {
$('#' + field).next().addClass('error_show');
} else if ($('#' + field).val()) {
$('#' + field).next().removeClass('error_show'); // <-- Here .removeClass() is added
data[field] = $('#' + field).val();
}
}
return false;
});
});
Now the class gets removed when the field has a value.
Demo: https://jsfiddle.net/mxjvu95n/1/

JQuery Validation on dynamic controls MVC

I have a problem validating dynamic addes inputs on GridView. I have partial views and each partial view has its own GridView. On my _Layout I have all links to scripts like jquery.validation.min.s etc. GridView is wrapped in a form so I have form id. Function for appending new row to GridView:
<script type="text/javascript">
$(function () {
$(document).on('click', '.addCostObject', function () {
var existRowSave = $('.saveCostObject').length;
var existRowEdit = $('.updateCostObject').length;
if (existRowSave == 0 && existRowEdit == 0) {
$('#gridCostObject tbody').append('<tr>' +
'<td><img src="#Url.Content("~/Images/save_.png")" /> <img src="#Url.Content("~/Images/save_cancel.png")" /></td>' +
'<td></td>' +
'<td><input type="text" name=\'costObject\' id=\'costObjectName\' class=\'costObjectNameClass\' placeholder=\'Cost Object Type\' data-val="true" data-val-required="This field is required"/></td>' +
'<td><input type="text" name=\'objectIdName\' id=\'objectId\' class=\'objectIdClass\' placeholder=\'Object ID\' data-val="true" data-val-required="This field is required"/></td>' +
'</tr>');
}
else {
alert('Save/Update or Cancel your previous record!');
}
})
event.stopImmediatePropagation();
})
At the end of my view I have a script for vaildating and appending rules:
<script type="text/javascript">
$(function() {
$("#gridCostObject").validate("add", {
rules: {
costObject: {
required: true
},
objectIdName: {
required: true,
digits: true
}
},
messages: {
objectIdName: {
digits: "Object id contains only digits"
}
}
})
})
At the save click, debugger always says that object form does not have 'valid'. I've tried putting my script everywhere in my view and trying all possible combination so far. What am I doing wrong?
$.validator.unobtrusive.parse('#yourFormSelector')
should help :)
It reinitializes the validation for your form - after that, the method will be available for your newly loaded elements

Form Hidden Field Substitution

I'm building a form using Expression Engine's Safecracker module.
One of the the required fields is the Title, which becomes the title of the EE channel entry.
What I'd like to do is set the Title field to be the combined first name and last name fields.
I started with this:
<form method="POST" action="#">
<input id="student_first_name" type="text" size="30" name="student_first_name">
<br>
<input id="student_last_name" type="text" size="30" name="student_last_name">
<br><br>
<input type="text" name="title" value=""/>
</form>
And then added this:
$(function() {
$('#student_first_name').keyup(function() {
var snamef = $(this);
});
$('#student_last_name').keyup(function() {
var snamel = $(this);
});
$("input[name='title']").val(snamel + " " + snamef);
return false;
});​
​I can't get it to work, though: http://jsfiddle.net/tylonius/CY5zJ/4/
Am I missing a step (or just totally doing it wrong?)?
Also, am I possibly working too hard and Safecracker already has this function built in; similar to its live UrlTitle(); function?
Any help is appreciated.
Thanks,
ty
If I understood right your question try this:
First set an id on your desired input element, like this :
<input type="text" name="title" id="student_title" value=""/>
And then :
$(function() {
changeFunction = function() {
$('#student_title').val($('#student_first_name').val() + ' ' + $("#student_last_name").val());
}
$('#student_first_name').keyup(changeFunction)
$('#student_last_name').keyup(changeFunction);
});
Better yet, avoid using javascript altogether and just use SafeCracker's dynamic_title parameter.
dynamic_title="[student_first_name] [student_last_name]"
user1236048 has the best solution for you but below is a working version of your code
$(function() {
var snamef;
var snamel;
$('#student_first_name').keyup(function() {
snamef = $(this).val();
$("input[name='title']").val(snamel + " " + snamef);
});
$('#student_last_name').keyup(function() {
snamel = $(this).val();
$("input[name='title']").val(snamel + " " + snamef);
});
return false;
});
and here is the working jsfiddle

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