Disable form fields on input into a group of other fields - javascript

I have the below form and would like to use jQuery to do the following:
1/ Disable the fields 'filter_from' and 'filter_to' if any character is entered into any one or more of the fields 'filter_loan_id', 'filter_fname', 'filter_lname', 'filter_postcode'.
2/ Re-enable the fields 'filter_from' and 'filter_to' only if there is no input in any of the fields 'filter_loan_id', 'filter_fname', 'filter_lname', 'filter_postcode'. That is, all 4 of these fields are empty.
I have the below code which works for point 1 - It disables the 2 fields when any of the other fields have data entered.
It does not work as required for point 2 - It currently re-enables the 2 fields if any one of the other fields is cleared. It should only re-enable the 2 fields when all of the other fields are cleared.
The fields 'filter_com' and 'filter_employer' should be ignored. They are only mentioned here to explain that not all of the fields on the form are to be used to disable the other 2 fields, just selected fields.
<form>
<input name="filter_from" type="text" autocomplete="off">
<input name="filter_to" type="text" autocomplete="off">
<input name="filter_loan_id" type="text" autocomplete="off">
<input name="filter_fname" type="text" autocomplete="off">
<input name="filter_lname" type="text" autocomplete="off">
<input name="filter_postcode" type="text" autocomplete="off">
<input name="filter_com" type="text" autocomplete="off">
<input name="filter_employer" type="text" autocomplete="off">
</form>
$(document).ready(function() {
$('input[name=filter_fname], input[name=filter_lname], input[name=filter_loan_id], input[name=filter_postcode]').change(function() {
if ($(this).val() != '') {
$('input[name=filter_from]').prop('disabled', true);
$('input[name=filter_to]').prop('disabled', true);
} else {
$('input[name=filter_from]').prop('disabled', false);
$('input[name=filter_to]').prop('disabled', false);
}
});
});

Try concatenating the values of all the relevant inputs and use that for checking
$(document).ready(function() {
var disableable = $('input[name=filter_from], input[name=filter_to]'),
valuable = $('input[name=filter_fname], input[name=filter_lname], input[name=filter_loan_id], input[name=filter_postcode]').on('input change', function() {
var combinedValue = valuable.get().map(function(element) {
return element.value;
}).join('');
disableable.prop('disabled', combinedValue !== '');
});
valuable.trigger('change');
});
input:disabled{background:#ccc;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
filter_from<input name="filter_from" type="text" autocomplete="off"><br> filter_to
<input name="filter_to" type="text" autocomplete="off"><br> filter_loan_id
<input name="filter_loan_id" type="text" autocomplete="off"><br> filter_fname
<input name="filter_fname" type="text" autocomplete="off"><br> filter_lname
<input name="filter_lname" type="text" autocomplete="off"><br> filter_postcode
<input name="filter_postcode" type="text" autocomplete="off"><br> filter_com
<input name="filter_com" type="text" autocomplete="off"><br> filter_employer
<input name="filter_employer" type="text" autocomplete="off">
</form>

Related

Check if an input with class is empty in a form

I wrote a code to validate a form on client-side. Since I binded all the error messages on('input', function()) now the last case to take in consideration is when the user didn't even hit a required input leaving it empty.
If all the inputs in the form were required I could have used something like
$('#subButton').on('click', function(e) {
if (!$('#formName').val()) {
e.preventDefault();
alert("Fill all the required fields");
});
But since in my form there are required inputs (with class="req") and non required inputs, I would like to know if there's a method to perform the check only on the .req inputs.
Something like:
$('#subButton').on('click', function(e) {
if (!$('#formName.req').val()) {
e.preventDefault();
alert("Fill all the required fields");
}
});
In other words I would like to perform the identical check which the up-to-date browsers do if the HTML required option is specified, just to be sure that, if the browser is a bit old and doesn't "read" the required option, jQuery prevents the form to be sent.
Just use .filter and check the length. Also, a simple ! check probably isn't good, what if someone enters 0?
var hasEmptyFields = $('#formName.req').filter(function() {
return this.value.replace(/^\s+/g, '').length; //returns true if empty
//Stole the above regex from: http://stackoverflow.com/questions/3937513/javascript-validation-for-empty-input-field
}).length > 0
if (hasEmptyFields) {
}
Use reduce
const submitAllowed = $('.req').toArray().reduce((result, item) => {
return result && (!!item.value || item.value === 0);
}, true)
if (!submitAllowed) { ... }
Here is a simple demo:
<form action="dummy.asp" onSubmit="return handleSubmit()">
<p> You can only submit if you enter a name </p>
<br />
Enter name: <input class="req" type="text" name="fname">
<input type="submit" value="Submit">
</form>
<script>
function handleSubmit() {
const submitAllowed = $('.req').toArray().reduce((result, item) => {
return result && (!!item.value || item.value === 0);
}, true)
return submitAllowed;
}
</script>
But since in my form there are required inputs (with class="req")
and non required inputs, I would like to know if there's a method to
perform the check only on the .req inputs
There is an HTML5 form boolean attribute required.
required works on:
<input type="text" />
<input type="search" />
<input type="url" />
<input type="tel" />
<input type="email" />
<input type="password" />
<input type="date" />
<input type="number" />
<input type="checkbox" />
<input type="radio" />
<input type="file" />
Example:
input {
display: block;
margin: 6px;
}
<form action="http://www.stackoverflow.com/">
<input type="text" placeholder="This is required" required />
<input type="text" placeholder="This isn't required" />
<input type="text" placeholder="This is required" required />
<input type="text" placeholder="This isn't required" />
<input type="submit" value="Press Me Without Filling in any of the Fields">
</form>
Peculiarly, the StackOverflow Snippet above doesn't seem to be working.
Here's a JSFiddle to demonstrate what it should be doing:
https://jsfiddle.net/a5tvaab8/

Populating error message with field name in Parsley js

I couldn't find anything in the Parsley docs or in Google.
Is there an easy way to set an attribute in input and populate the error message with custom message.
For example:
<label>First name
<input type="text" required/>
</label>
with give a standard error "This value is required."
But it would be nice to have something like
<label>First name
<input type="text" required data-parsley-field-name="Last name"/>
</label>
with error like "Last name is required"
Or as an option, just grad string from<label>.
I know that I can set custom messages, but you have to do it on each input.
This will your job
<form method="post" id="myForm">
<input type="text" name="phone" class="form" data-err="last name" value="" class="required" data-parsley-required="" />
<input type="text" name="phone" class="form" data-err="First name" value="" class="required" data-parsley-required="" />
<input type="submit" value="Go">
$(document).ready(function() {
$("#myForm").parsley();
$.listen('parsley:field:error', function(){
var i = 0;
$("#myForm .form").each(function(k,e){
var field = $(e).data("err");
$(e).next("ul").find("li:eq("+i+")").html(field+" is required");
});
});
});
here is working fiddle JsFiddle

Walk through a form in javascript and check for blank inputs?

I apologize for asking such a "noob" question but I'm outside my area of expertise here.
I'm using Dojo 1.9 and I need to walk through a submitted form and determine if any of the input fields are blank. The tricky part is that the form is dynamic, it can contain an array of child elements of each array element, with names like itemList[1].myName:
<form id="businessReferences" action="/yabba/dabba/doo" method="post">
<input id="itemList[0].myName" name="itemList[0].myName" type="text" value=""/>
<input id="itemList[0].myAddress" name="itemList[0].myAddress" type="text" value=""/>
<input id="itemList[1].myName" name="itemList[1].myName" type="text" value=""/>
<input id="itemList[1].myAddress" name="itemList[1].myAddress" type="text" value=""/>
<input id="itemList[2].myName" name="itemList[2].myName" type="text" value=""/>
<input id="itemList[2].myAddress" name="itemList[2].myAddress" type="text" value=""/>
</form>
What is the best way to walk through this form and check to see if all the fields for each parent element are empty? For example if all the fields for itemList[2] are empty? Is there a particular method for doing this? Seems like it would be a fairly common problem but I haven't been able to track down an answer.
Just add an submit button in the form
<form id="businessReferences" action="/yabba/dabba/doo" method="post" onsubmit="return validate()">
<input id="itemList[0].myName" name="itemList[0].myName" type="text" value=""/>
<input id="itemList[0].myAddress" name="itemList[0].myAddress" type="text" value=""/>
<input id="itemList[1].myName" name="itemList[1].myName" type="text" value=""/>
<input id="itemList[1].myAddress" name="itemList[1].myAddress" type="text" value=""/>
<input id="itemList[2].myName" name="itemList[2].myName" type="text" value=""/>
<input id="itemList[2].myAddress" name="itemList[2].myAddress" type="text" value=""/>
<input type='submit' value="Submit"/> <!-- to trigger validation on this button click -->
</form>
Javscript for validation , it will account for dynamically added element also
<script type='text/javascript'>
function validate(){
FromRef = document.getElementById('businessReferences');
for(i=0; i<FromRef.elements.length; i++)
{
if((FromRef.elements[i].value).trim() ==""){ // see if the value is blank popup and alert
alert( FromRef.elements[i].name +"is required");
return false; // not to submit form
}
return true;//submit form
}
</script>

How to validate a form in jsp using javascript before submit

<form name="Details" method="post" action="insertData.jsp" onSubmit="return ValidateForm();">
<label> Name </label > <input type="text" name="name" id="test1" > </input>
<label> ID </label > <input type="text" name="id" id="test2" > </input>
<label> Time </label > <input type="text" name="time" id="test3" > </input>
<label> Latitude </label > <input type="text" name="latitude" id="test4" > </input>
<label> Longitude </label > <input type="text" name="longitude" id="test5" > </input>
<input type= " submit" id="test6" value="submit" > </input>
Validation code in js
function ValidateForm()
{
var uname=document.Detail.name;
if(alphanumeric(uname)){
}
return false;
}
function alphanumeric(uname){
var letter=/*[0-9a-zA-Z]+$/;
if(uname.value.match(letter)){
return true;
}
else{
aler("Enter both alpha and number");
uname.focus();
return false;
}
}
The above validation is to allow a textfield to accept both alphabets and numbers but not only numbers. Its returning false on a wrong input but still the data entered entered is submitted to the database. How to avoid this? what is wrong in my code?
I also want to validate form before submit. After every field is entered it should be validated and displayed if any error just below the field. How do i do it?
You could use a naming pattern for the Ids of hidden <span> tags that represent the form field error messages:
<form onsubmit="return ValidateForm(this);">
<p>
<input type="text" id="name" name="name">
<span style="display: none;" id="name-validation-message"></span>
</p>
</form>
<script>
function ValidateForm(form) {
if (!alphanumeric(form.elements.name)) {
var message = document.getElementById(form.elements.name.id + "-validation-message");
message.innerHTML = "Must be alphanumeric";
message.style.display = "";
}
}
</script>
The elements property on form objects is a key-value store where the keys are the values of the name attribute on the form fields, and the values are either a reference to a single form field DOM node, or a collection.
Consider the following HTML:
<form id="test">
<input type="text" name="foo">
<input type="checkbox" name="bar" value="1">
<input type="checkbox" name="bar" value="2">
<input type="checkbox" name="bar" value="3">
<input type="checkbox" name="bar" value="4">
<input type="text" name="things[]">
<input type="text" name="things[]">
<input type="text" name="things[]">
<input type="text" name="things[]">
<input type="text" name="things[]">
<input type="text" name="things[]">
<input type="text" name="things[]">
</form>
We have three unique form field name attribute values:
foo
bar
things[]
In JavaScript, we'll have the following object model:
var form = document.getElementById("test");
form.elements; // A collection of references to all form fields
form.elements.foo; // Reference to <input type="text" name="foo">
// A DOM node collection referencing all checkboxes whose name is "bar"
form.elements.bar;
form.elements.bar[0]; // First "bar" checkbox
form.elements.bar[1]; // Second "bar" checkbox
// A DOM node collection referencing all text boxes whose name is "things[]"
form.elements["things[]"];
form.elements["things[]"][0]; // First "things[]" textbox
form.elements["things[]"][1]; // Second "things[]" textbox
Many server side languages turn field names with square brackets into arrays. You can access those fields in JavaScript using the Array Notation (e.g. form.elements["bar"] instead of Dot Notation (e.g. form.elements.bar).
Hope the following code helps.
<HTML>
<HEAD>
<TITLE>Verifying User Data</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function checker()
{
var regExp1 = '/^(\d{1,2})\/(\d{1,2})\/(\d{2})$/' ;
var result1 = document.form1.text1.value.match(regExp1);
if (result1 == null || <*any other input doesnt satisfy the required format*>) {
alert("Sorry, that's not a valid date.");
document.form1.text1.focus(); // or document.<formname>.<element_name>.focus();
return;
} else {
document.form1.action="<NextPage.jsp>" ;
document.form1.method="GET"; // or "POST"
document.form1.submit();
}
}
</SCRIPT>
</HEAD>
<BODY>
<H1>Verifying User Data</H1>
<FORM NAME="form1" >
Please enter a date:
<INPUT TYPE="TEXT" NAME="value1">
<INPUT TYPE="<sometype>" NAME="value2">
<INPUT TYPE="<sometype>" NAME="value3">
..
..
<INPUT TYPE="button" onclick="checker()">
</FORM>
</BODY>
Write another javascript on submit button like
<input type= " submit" id="test6" value="submit" onclick="return save();">
<script>
function save(){
document.form[0].submit;
}
</script>

Remove unchanged input fields from Form while submit

In my web application I have edit profile page. In editprofile page their is many fields like
Name : <input type="text" name="name"/>
Location : <input type="text" class="geolocation" name="location">
Birthdata : <input type="date" name="dob">
Profile Picture : <input type="file" name="photo"/>
I want to send back the data of only the fields which are edited and not all the fields.
I'd normally do something like this on the backend.... but for your requirement you could remove the inputs that haven't changed. When you generate the html you can define an extra data attribute. Here's how I would do that:
HTML:
<form id="myform">
<input type="text" id="Name" data-initial="Foo" value="Foo" />
<input type="text" id="Location" data-initial="Bar" value="Bar" />
<input type="submit" value="Submit" />
</form>
JS:
$("#myform").submit( function() {
$(this).find("input").filter( function() {
$this = $(this);
return $this.data("initial") == $this.val();
}).remove();
});
http://jsfiddle.net/uLe7T/
I added an alert in the fiddle so you can see that they are removed before the form is submitted
jsFiddle
HTML
<input id="test" type="text" value="Some Text" data-value="Some Text">
JS
$('#test').blur(function() {
el = $(this);
if (el.val() != el.attr('data-value')) {
console.log('Edited');
} else {
console.log('Not Edited');
}
});

Categories