jQuery form validation - javascript

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

Related

jquery validation enable form when all fileds valid : do no show error for empty fileds

I want button to enable if all fields are valid, as no button enable and disable works fine, but when I move to next fields it highlights error for all fields, but I do not want this to happend any way to fix it, please guide way for it.
JS code:
$(document).ready(function() {
$('input').on('blur', function() {
if ($("#myform").valid()) {
$('#submit').prop('disabled', false);
} else {
$('#submit').prop('disabled', 'disabled');
}
});
$("#myform").validate();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script>
<form id="myform">
<input type="text" id="name2" name="name2" class="required" />
<br/>
<input type="text" id="name" name="name" class="required email" />
<br/>
<input type="text" id="name1" name="name1" class="required number" />
<br/>
<input type="submit" id="submit" disabled="disabled" />
</form>
at the end of input you also have to click outside to form that will blur and will validate . otherwise it won't work
$(document).ready(function() {
$('input').on('blur', function() {
if ($("#myform").valid()) {
$('#submit').prop('disabled', false);
} else {
$('#submit').prop('disabled', 'disabled');
}
});
$("#myform").validate();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>
<form id="myform">
<input type="text" id="name2" name="name2" class="required"/><br/>
<input type="text" id="name" name="name" class="required email"/><br/>
<input type="text" id="name1" name="name1" class="required number"/><br/>
<input type="submit" id="submit" disabled="disabled" />
</form>
The issue is that you are validating the entire form , this would validate all the fields at the same time. You need to loop through each input and explicitly check each field to see if they are valid. If all of them are valid, only then enable submit button.
$(document).ready(function() {
$('input').on('blur', function() {
var allowSubmission = true;
$("input").each(function() {
if(!$(this).valid())
{
allowSubmission = false;
return false;
}
});
if(allowSubmission)
$('#submit').prop('disabled', false)
else
$('#submit').prop('disabled', true)
});
});
Example : http://jsfiddle.net/sd88wucL/109/

validation of form inputs in JavaScript

I want to validate a input fields of form in javascript. I have searched a lot on net and always got different ways to do it. It was so confusing. I want for every single input if it is left empty an alert should popup. Here is my code
<form method="post" action="form.html" id="FormContact" name="frm">
<p>Full Name: <br /><br /> <input type="text" name="FullName" size="50" id="Name"></p>
<span id="error"></span>
<p>Email:<br /><br /> <input type="email" name="Email" size="50" id="Mail"></p>
<p> Subject:<br /><br /> <input type="text" name="subject" size="50" id="Subject"></p>
Message:<br /><br />
<textarea rows="15" cols="75" name="Comment" id="text">
</textarea> <br /><br />
<input type="submit" value="Post Comment">
</form>
I got it done sometimes but that only worked for Full Name field.
Thanks and regards,
You can do something like this, to have an alert popup for each empty input.
$('form').on('submit', function(){
$('input').each(function(){
if($(this).val() === ""){
alert($(this).attr('name') + " is empty");
}
});
});
http://www.w3schools.com/js/js_form_validation.asp
if you're willing to use javascript, this would be pretty easy to implement.
use jquery validation plugin.
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script>
$("#FormContact").validate({
rules: {
FullName: {
required:true
}
},
messages:{
FullName:{
required:"Please Enter FullName."
}
}
});
</script>
USE submit method of jquery the use each loop to validate the controls
LIVE CODE
$('form#FormContact').submit(function(){
var i= 0;
$('input').each(function(i,j){
if($(this).val() == "" || $(this).val() == undefined){
alert('empty');
i++;
}else{
i=0;
}
})
if(i == 0){
return false;
}else{
return true;
}
})

JavaScript function uses simply "true". How does this work in this example?

This is simply a form. The code tests if all the required fields a filled in. Specifically, I don't understand the test on the keyup. What is it testing? Simply is something is typed into the input field?
<p>
<label for="name">Name:</label>
<input name="name" id="name" type="text" class="required">
<span>Please enter your name</span>
</p>
<p class="submit">
<input type="submit" value="Submit" class="btn-submit">
</p>
<script>
var $submit = $(".submit input");
function requiredFilledIn() {
if(true) $submit.attr("disabled", "disabled");
else $submit.removeAttr("disabled");
}
$("#form span").hide();
$("input, textarea").focus(function () {
$(this).next().fadeIn("slow");
}).blur(function(){
$(this).next().fadeOut("slow");
}).keyup(function(){
//Check all required fields.
requiredFilledIn();
});
$("#email").onkeyup(function(){
if (true) $(this).next().removeClass("error").addClass("valid");
else $(this).next().removeClass("valid").addClass("error");
});
requiredFilledIn();
</script>

jquery find input before button

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/

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