jquery find input before button - javascript

I have a single form on the page and I have some jQuery to make sure that the inputs have been completed before the submit.
But now I need to have multiple similar forms repeated on the page and I need to change the jQuery to only check the two inputs in the form that the button was clicked and not check any other form on the page.
<div class="offerDate">
<form class="form-inline hidden-phone" action="http://www.treacyswestcounty.com/bookings/" method="get">
<fieldset>
<input type="text" name="from_date" placeholder="dd/mm/yy" id="from_date" class="input-small hasDatepicker">
<input type="text" name="to_date" placeholder="dd/mm/yy" id="to_date" class="input-small hasDatepicker">
<button id="submitDates" class="btn btn-main" type="submit">CHECK NOW</button>
</fieldset>
</form>
</div>
<div class="offerDate">
<form class="form-inline hidden-phone" action="http://www.treacyswestcounty.com/bookings/" method="get">
<fieldset>
<input type="text" name="from_date" placeholder="dd/mm/yy" id="from_date" class="input-small hasDatepicker">
<input type="text" name="to_date" placeholder="dd/mm/yy" id="to_date" class="input-small hasDatepicker">
<button id="submitDates" class="btn btn-main" type="submit">CHECK NOW</button>
</fieldset>
</form>
</div>
The jQuery that I have used previously to check on form using ID
// validate signup form on keyup and submit
jQuery('#submitDates').click(function () {
var found = false;
jQuery("#to_date, #from_date").each(function(i,name){
// Check if field is empty or not
if (!found && jQuery(name).val()=='') {
alert ('Please choose your arrival and departure dates!')
found = true;
} ;
});
return !found;
});

.prev( [selector ] )
Returns: jQuery
Description: Get the immediately preceding sibling of each element in
the set of matched elements, optionally filtered by a selector.
This is quite short and will target any input displayed just before a button :
$("button").prev("input")
jsFiddled here

you can try like this:
CODE
jQuery('.submitDates').click(function () {
var found = false;
jQuery(this).siblings("input").each(function (i, name) {
// Check if field is empty or not
if (!found && jQuery(name).val() == '') {
alert('Please choose your arrival and departure dates!')
found = true;
};
});
return !found;
});
assuming your inputs are siblings for the button. Note I also changed button's id into class.
FIDDLE http://jsfiddle.net/FY9P9/

Closest and Find do it as well, wherever the input are for the button :
HTML:
<form class="form">
<input type="text" class="toDate" />
<input type="text" class="fromDate" />
<div class="button">Click</div>
</form>
<form class="form">
<input type="text" class="toDate" />
<input type="text" class="fromDate" />
<div class="button">Click</div>
</form>
JS:
$(".button").each(function () {
$(this).click(function () {
if (($(this).closest(".form").find(".toDate").val() == "") || ($(this).closest(".form").find(".fromDate").val() == "")) {
alert("Please fill in arrival and departure Date");
}
})
})
http://jsfiddle.net/GuqJF/1/

Related

Validation field setCustomValidity() method

I have to do the validation of the input text field.
I would like Js to show an error message through the setCustomValidity() method.
Is it possible?
function checkName() {
var x = document.formUser;
var input = x.name.value;
if (input.length < 3) {
input.setCustomValidity('This field is invalidate');
return false;
}
}
<form name="formUser" id="formUser" action="#" method="POST" onsubmit="return validateForm();">
<div class="section">
<label for="fname">Nome</label>
<input class="form-control" type="text" id="name" required>
</div>
<input type="submit" class="btn btn-primary" value="Invia" onclick="validateForm();">
</form>
You need to call reportValidity() on the input after setting the custom validity message.
Additionally you must call the reportValidity method on the same element or nothing will happen.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement/setCustomValidity#examples
function checkName() {
const inp = document.getElementById('name');
const val = inp.value;
if (val.length < 3) {
inp.setCustomValidity('This field is invalidate');
inp.reportValidity();
return false;
}
}
<form name="formUser" id="formUser" action="#" method="POST" onsubmit="return checkName();">
<div class="section">
<label for="fname">Nome</label>
<input class="form-control" type="text" id="name" required>
</div>
<input type="submit" class="btn btn-primary" value="Invia" onclick="checkName();">
</form>
I would like to control more text input with javascript.
The setCustomValidity() method means that it will have to show an error message if input has less than three characters.
it doesn't always work.
Eg. If I put a string of one character in the first field and a string of four in the second field; it sends without showing the error. If I repeat the same test, it works.
Why?
window.onload = function() {
const field = document.getElementsByClassName("input-field");
for (let i = 0; i < field.length; i++) {
field[i].addEventListener('input', function() {
const val = field[i];
if (val.length < 3) {
field[i].setCustomValidity('Field is invalid');
}
})
}
}
<form name="formUser" id="formUser" action="#">
<div class="section">
<label for="fname">First name</label>
<input class="form-control input-field" type="text" id="fname" required>
<label for="lname">Last name</label>
<input class="form-control input-field" type="text" id="lname" required>
</div>
<input type="submit" class="btn btn-primary" value="Send">
You could add a <p class="error">...</p> inside your section div.
Hide it with css (display: none) and when you get an error in your validation add a class to that like "show" to show it (display: unset).
You can do custom form validation using Javascript like this.
Here I have just added a div with a warning and alert box. You can do whatever you want.
It will alert a warning if you will click on submit when fields were empty.
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
let alertBox = document.getElementById("alert-box");
// Here instead of checking (x == " "), you can use your custom validations
if (x == "") {
alertBox.innerHTML = `<p>Form input are empty</p>`; // appends a div with warning
alert("Name must be filled out"); // alert box
return false;
}
}
</script>
</head>
<body>
<h2>JavaScript Validation</h2>
<div id="alert-box"> </div>
<form name="myForm" action="#" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>

Jquery to check if form fields are required before modal pop up

Hi have a form which has two submit buttons:
(Button 2)The user clicks the submit button and a modal pop up appears and in the modal is some T&Cs they have to accept, (Button 1) once they click accept the second submit button does the form submission.
There are required form fields that don't show (required) once the first button is pressed just the modal pop up comes, How can I achieve this? My Jquery code is:
$(document).ready(function () {
$("#login-form button").click(function (ev) {
ev.preventDefault()
if ($(this).attr("value") == "button1") {
// alert("First Button is pressed")
$("#login-form").submit();
}
if ($(this).attr("value") == "button2") {
$(".modal").addClass("active");
}
});
});
The form field is:
<label class="form-label" for="firstname">First name:</label>
<input class="form-input" required type="text" name="firstname" id="firstname" value="firstname>
Any ideas?
Here is a little code i wrote, i try to make it as dynamic as possible.
Instead of click you should have it onchange but its really upp to you.
make sure too look at validationType
$("input[type='button']").click(function(){
if ($(this).hasClass("disable"))
return false;
if ($(this).hasClass("validate")){
var errors = [];
// all required input that need validation
var input = $(this).parent().find("input[type='text'][required='required']");
input.each(function(){
var vType= $(this).attr("validationType");
var value =$(this).val();
var fName =$(this).attr("placeholder");
switch(vType){
case "notEmpty":
if (!value || value== "")
errors.push(fName +" cant be empty");
break;
}
});
if (errors.length>0){
$(this).parent().find(".submit").addClass("disable");
alert(errors)
}
else {
$(this).parent().find(".submit").removeClass("disable");
}
}else return true; // submit the form
});
input[required="required"]{
border:1px solid red;
}
.disable{
color:#CCC;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" validationType="notEmpty" required="required" value="" placeholder="firstName" />
<input type="button" class="validate" value="button 1" />
<input type="button" class="submit disable" value="button 2" />
</form>
Ok this is how steps works on my own way .. The idea here is the first form is a main one and the second is a just for users not for programming .. This means the first form will have all the required fields and I will hide the fields and control it with javascript from the fake form
I create two forms one is a main and the second is a fake one
I add a hidden checkbox in a main form
I make separated submit events for each form
I made a change event for the fake checkbox to control the main checkbox in the main form
$(document).ready(function(){
// Main Form Submit
$("#mainForm").on("submit" , function(e){
e.preventDefault();
if($("#mainCheck").is(":checked")){
alert("First Form is Submitted correctly");
}else{
//alert('Show Modal With Form');
$("#fakeForm").show();
}
});
// Fake form in Modal submit
$("#fakeForm").on("submit" , function(e){
e.preventDefault();
if($("#fakeCheck").is(":checked")){
$("#mainForm").submit();
}else{
alert("Please Accept our policies first");
}
});
// fake checkbox to change main checkbox
$("#fakeCheck").on("change" , function(){
$("#mainCheck").prop("checked" , this.checked);
});
});
#mainForm, #fakeForm{
background : #eee;
border : 5px solid #555;
margin : 20px;
padding : 20px;
}
#mainCheckLabel,#fakeForm{
display : none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- first Form -->
<form id="mainForm">
<label class="form-label" for="firstname">First name:</label>
<input class="form-input" required type="text" name="firstname" id="firstname" value="firstname" />
<br/>
<label id="mainCheckLabel"><input type="checkbox" id="mainCheck"/>Accept to our policies</label>
<button type="submit">Submit First Form</button>
</form>
<!-- End First Form -->
<!-- Second Form in Modal -->
<form id="fakeForm">
<label id="fakeCheckLabel"><input type="checkbox" id="fakeCheck"/>Accept to our policies</label>
<button type="submit">Submit Second Form</button>
</form>
<!-- End Second Form in Modal -->
Note hide the #mainCheckLabel in the main form
Example of how to use [required] selector
$('input[required]').css('border' , '1px solid red');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" required placeholder="First Name"/>
<input type="text" placeholder="Last Name"/>
Following solution works for me:
$("#uploadBtn").click(function() {
var form_data = new FormData($("#data-uploader-form")[0])
if ($("#data-uploader-form")[0].checkValidity()) {
alert("valid form")
} else {
alert("incorrect form")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id='data-uploader-form' onsubmit='return false;'>
<div class="form-group row">
<label>Input field</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="testInputField" placeholder="some text" required="required">
</div>
</div>
<div class="form-group row">
<label class="col-12 col-lg-3 col-form-label"></label>
<div class="col-12 col-lg-6">
<button type="submit" class="btn btn-primary float-left" id="uploadBtn">Submit</button>
</div>
</div>
</form>

How do I show/hide a div on field validation with parsley.js

So I guess for context, here is an example from the parsley.js documentation.
<form id="demo-form" data-parsley-validate>
<div class="first">
<label for="firstname">Firstname:</label>
<input type="text" name="firstname" data-parsley-range="[4, 20]" data-parsley-group="block1" />
<label for="lastname">Lastname:</label>
<input type="text" name="lastname" data-parsley-range="[4, 20]" data-parsley-group="block1" />
</div>
<hr></hr>
<div class="second">
<label for="fullname">Fullname:</label>
<input type="text" name="fullname" data-parsley-range="[8, 40]" data-parsley-group="block2" />
</div>
<div class="invalid-form-error-message"></div>
<input type="submit" class="btn btn-default validate" />
</form>
<script type="text/javascript">
$(document).ready(function () {
$('#demo-form').parsley().subscribe('parsley:form:validate', function (formInstance) {
// if one of these blocks is not failing do not prevent submission
// we use here group validation with option force (validate even non required fields)
if (formInstance.isValid('block1', true) || formInstance.isValid('block2', true)) {
$('.invalid-form-error-message').html('');
return;
}
// else stop form submission
formInstance.submitEvent.preventDefault();
// and display a gentle message
$('.invalid-form-error-message')
.html("You must correctly fill the fields of at least one of these two blocks!")
.addClass("filled");
return;
});
});
</script>
Let's say I have a hidden div called "checkmark". How would I show this div upon validation of the firstname field?
I should also clarify that I have read the documentation, but still don't understand how to accomplish what I'm trying to do here, so posting a link to the documentation is not really going to be helpful unless you are using it in your answer.
You should use Parsley's Events. Since you want to display or hide something based on a field validation, you should use parsley:field:success and parsley:field:error.
Working example (with jsfiddle):
<form id="demo-form" data-parsley-validate>
<div class="first">
<label for="firstname">Firstname:</label>
<input type="text" name="firstname" data-parsley-range="[4, 20]" data-parsley-group="block1" required />
<div class="hidden" id="checkmark">This message will be shown when the firstname is not valid </div>
<label for="lastname">Lastname:</label>
<input type="text" name="lastname" data-parsley-range="[4, 20]" data-parsley-group="block1" />
</div>
<hr></hr>
<div class="second">
<label for="fullname">Fullname:</label>
<input type="text" name="fullname" data-parsley-range="[8, 40]" data-parsley-group="block2" />
</div>
<div class="invalid-form-error-message"></div>
<input type="submit" class="btn btn-default validate" />
</form>
<script>
$(document).ready(function () {
$('#demo-form').parsley().subscribe('parsley:form:validate', function (formInstance) {
// if one of these blocks is not failing do not prevent submission
// we use here group validation with option force (validate even non required fields)
if (formInstance.isValid('block1', true) || formInstance.isValid('block2', true)) {
$('.invalid-form-error-message').html('');
return;
}
// else stop form submission
formInstance.submitEvent.preventDefault();
// and display a gentle message
$('.invalid-form-error-message')
.html("You must correctly fill the fields of at least one of these two blocks!")
.addClass("filled");
return;
});
$.listen('parsley:field:error', function(ParsleyField) {
if(ParsleyField.$element.attr('name') === 'firstname') {
$("div#checkmark").addClass('show').removeClass('hidden');
}
});
$.listen('parsley:field:success', function(ParsleyField) {
if(ParsleyField.$element.attr('name') === 'firstname') {
$("div#checkmark").addClass('hidden').removeClass('show');
}
});
});
</script>
And here's what I did:
Added a div with ìd=checkmark after the firstname field (with a hidden class, since you're using Bootstrap).
Added this block of javascript:
$.listen('parsley:field:error', function(ParsleyField) {
if(ParsleyField.$element.attr('name') === 'firstname') {
$("div#checkmark").addClass('show').removeClass('hidden');
}
});
$.listen('parsley:field:success', function(ParsleyField) {
if(ParsleyField.$element.attr('name') === 'firstname') {
$("div#checkmark").addClass('hidden').removeClass('show');
}
});
This code will listen to the validation of every input validated by Parsley. This means that when the field lastname fails, the code inside $.listen('parsley:field:error', function(ParsleyField) { will be executed. This is why I used an if to check if the attr name is firstname.
Then you show or hide the div based on the validation result.
Added required to the field, so the message is displayed when you click on the button.

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');
}
});

jQuery form validation

I have been working on this jQuery form which would only allow the user to submit once all fields are filled in. So essentially, the submit field (or in my case the 'request' field) is dimmed until all fields are not blank. My button is always dimmed though, would someone help me with this please? I have the following jQuery:
$(function() {
var $submit = $(".request input");
var $required = $(".required");
function containsBlanks(){
var blanks = $required.map(function(){ return $(this).val() == "";});
// the inArray helper method checks if value is within an array
return $.inArray(true, blanks) != -1;
}
function requiredFilledIn(){
if(containsBlanks())
$submit.attr("disabled","disabled");
else
$submit.removeAttr("disabled");
}
$("#form2 span").hide();
$("input").focus(function(){
$(this).next().fadeIn("slow");
}).blur(function(){
$(this).next().fadeOut("slow");
}).keyup(function(){
//Check all required fields.
requiredFilledIn();
});
requiredFilledIn();
});
This is my form
<div id="form2" title="Request a Call-back">
<p class="validateTips">All form fields are required. The submit button will activate once this is done.</p>
<form action="includes/requestcall.php" method="post">
<fieldset>
<label for="name">Name:</label>
<input type="text" name="name" id="name" size="30" class="required" />
<span>Please enter your Name</span>
<br />
<br />
<label for="number">Number:</label>
<input type="text" name="number" id="number" size="30" class="required" />
<span>Please enter your number</span>
<br />
<br />
<label for="time">Preferred Time:</label>
<input type="text" name="time" id="time" size="30" class="required" />
<span>Please enter your preferred time</span>
<br />
</fieldset>
<p class="request">
<input type="submit" value="Request" class="btn-submit">
</p>
</form>
</div>
I'm still learning jQuery and any help would be much appreciated.
I've adjusted the code slightly to use the filter function to retrieve the empty textboxes along with using the change event.
This is the link to the updated script running your markup on JSFiddle
Here's the updated script:
$(function () {
var $submit = $("input.btn-submit").attr("disabled", "disabled").css("color", "red");
var $required = $(".required");
function requiredFilledIn() {
var blanks = $required.filter(function () {
return $(this).val() === "";
});
if (blanks.length > 0) $submit.attr("disabled", "disabled").css("color", "red");
else $submit.removeAttr("disabled").css("color", "black");
}
$("#form2 span").hide();
$("input:text").focus(function () {
$(this).next().fadeIn("slow");
}).blur(function () {
$(this).next().fadeOut("slow");
}).change(function () {
//Check all required fields.
requiredFilledIn();
});
});

Categories