Happy.js - adding a message below submit button - javascript

Awesome people of Stack Overflow,
I'm trying to use Happy.js for validating my form, and it works fine. However, since my form is long and the submit button is at the very bottom of the form, I need a way to let the user know that there a errors on the form.
I'd love some help adding this functionality. Maybe unhiding a div right below the submit button or something like that.
Here's the HTML:
<form name="data" action="#" method="POST" id="JumpstartForm">
<label for="f1" class="control-label">First Name<span class='required'>*</span> </label>
<input title="First Name" type="text" id="f1" name="First_Name" class="input-large" value="" size="25" />
<div class="centered"><input type="submit" id="submitSignup" value="Submit" class="green-button" /></div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://www.democracy-nc.org/jumpstart/js/happy.js"></script>
<script src="http://www.democracy-nc.org/jumpstart/js/happy.methods.js"></script>
Here's the js bit:
$(document).ready(function () {
$('#JumpstartForm').isHappy({
fields: {
// reference the field you're talking about, probably by `id`
// but you could certainly do $('[name=name]') as well.
'#f1': {
required: true,
message: 'Please enter your first name'
},
}
});
});
I created a JSfiddle: http://jsfiddle.net/gcasalett/E9Lq7/1/
Live page: http://democracy-nc.org/jumpstart/index.html
First post, so please be kind. Thanks!

What you need it's to use the callback that the plugin provide, called unHappy that it's called when the validation fails for any reason.
For other options you can check the Happy.js mainpage http://happyjs.com/
$(document).ready(function () {
$('#JumpstartForm').isHappy({
fields: {
// reference the field you're talking about, probably by `id`
// but you could certainly do $('[name=name]') as well.
'#f1': {
required: true,
message: 'Please enter your first name'
},
unHappy: function () {
//here you can show a div, or scroll to the last error.
},
}
});
});
Updated jsFiddle : http://jsfiddle.net/E9Lq7/4/

Related

Bootstrap jQuery - Issues with empty field validation

I've written some jQuery to validate my Bootstrap forms, however I'm having a few issues.
Firstly, I want a red outline to appear if the user clicks off the input field without typing anything in: JSFiddle example here. In this example I'm using the Bootstrap Validator plugin, however I want to imitate this effect without using the plugin.
Second, and linked to the issue I just mentioned, the green outline only appears once the user clicks the submit button, thus the user only sees it for half a second or so before they are redirected, making it a little pointless. Again, this would be solved by having an error/success outline appear once the user clicks off the input. If anyone could help me out it would be greatly appreciated.
This is the code I have so far:
HTML:
<form id="auth_form" action="action.php" method="post">
<div class="form-group has-feedback" name="auth_code" id="auth_code">
<label for="auth_code" class="control-label">
Authorisation Code</label>
<input class="form-control" id="auth_code_input" name="auth_code_input" type="password">
<span class="form-control-feedback glyphicon" id="iconBad"></span>
</div>
<div class="form-group">
<div>
<button class="btn btn-info" name="submit" type="submit" id="submit">Submit</button>
</div>
</div>
</form>
jQuery:
$(document).ready(function() {
$('#auth_form').on('submit', function(e) {
var auth_code = $('#auth_code_input').val()
if (auth_code=="") {
$('#auth_code').addClass('has-error');
$('#iconBad').removeClass('glyphicon-ok').addClass('glyphicon-remove');
e.preventDefault();
} else {
$('#auth_code').removeClass('has-error').addClass('has-success');
$('#iconBad').removeClass('glyphicon-remove').addClass('glyphicon-ok');
}
})
})
JSFiddle
Try this updated fiddle: jsfiddle.net/xqwsobmo/20/
Need to add input blur event and validate input
$(document).ready(function() {
$('#auth_code_input').blur(function(){
if(!ValidateInput()){
e.preventDefault();
}
});
$('#auth_form').on('submit', function(e) {
if(!ValidateInput()){
e.preventDefault();
}
})
});
function ValidateInput(){
var IsValid=false;
var auth_code = $('#auth_code_input').val()
if (auth_code=="") {
$('#auth_code').addClass('has-error');
$('#iconBad').removeClass('glyphicon-ok').addClass('glyphicon-remove');
IsValid=false;
} else {
$('#auth_code').removeClass('has-error').addClass('has-success');
$('#iconBad').removeClass('glyphicon-remove').addClass('glyphicon-ok');
IsValid=true;
}
return IsValid;
}

.Validate jQuery Validation Plugin not Ignoring Hidden Fields

I'm new to jQuery and the .Validate jQuery Validation Plugin. I'm trying to integrate it into a multi-step form. Basically, I've set up a switch based on which next button the user presses and want to validate only that specific part of the form based on that.
When I successfully validate the first part of the form and move onto the second fieldset, the next set of fields come up already throwing validation errors. I've tried disabling the fields (which prevents the slider logic I'm using from working for some reason), specifically telling it to ignore that fieldset by class and directly declaring ignore: ":hidden" even though it's the default behavior.
I've placed the code I'm having trouble with in a jsFiddle here: http://jsfiddle.net/13x7Lbk7/4/ (updated)
Here is the specific part of my code that calls validation for the first step of the form:
$(".next").click(function(){
// Initialize form
var form = $("#frmSignup");
// Determine which step of the form we're on
switch($(this).attr("value")) {
case "step1":
$("#frmSignup").validate({
rules: {
txtZipCode: {
required: true,
number: true,
minlength: 5,
maxlength: 5,
},
txtSchoolName: {
required: true,
minlength: 5,
},
},
messages: {
txtZipCode: {
required: "Zip Code Required",
number: "Enter a valid 5 digit zip code",
minlength: "Enter a valid 5 digit zip code",
},
txtSchoolName: {
required: "School Name Required",
},
},
});
break;
// --- SNIP ---
} // End step switch
if ($("#frmSignup").valid() == true){
// Fieldset logic is here, see jsFiddle if you're curious
} // End isValid if
}); // End click function
And here is the relevant HTML for the first two fieldsets:
<fieldset class="fsStep1">
<h2>Step 1</h2>
<h3>Information</h3>
<label for="txtZipCode">Zip Code</label>
<input type="text" name="txtZipCode" value="" pattern="\d*" id="txtZipCode" required />
<label for="txtExample">Example Field</label>
<input type="text" name="txtExample" value="" id="txtExample" required />
<hr />
<button name="next" value="step1" class="next action-button">Next</button>
</fieldset>
<fieldset class="fsStep2">
<h2>Step 2</h2>
<h3>Example</h3>
<label for="txtInfo">Info</label>
<input type="text" name="txtInfo" id="txtInfo" value="" pattern="[a-zA-Z -]+" required />
<label for="txtOther">Other</label>
<input type="text" name="txtOther" id="txtOther" value="" pattern="[a-zA-Z -]+" required />
<hr />
<input type="button" name="previous" class="previous action-button" value="Previous" />
<button name="next" value="step2" class="next action-button">Next</button>
</fieldset>
I'm sure I'm missing something boneheaded here, but I keep going through the code, reviewing documentation, searching the web and I've been coming up against a blank wall all day. Please put me out of my mysery and tell me exactly why I'm stupid. :) Thank you!
Ok, if it does not like hidden fields, use this trick to hide them:
/*Hide all except first fieldset*/
#frmSignup fieldset:not(.shown) {
height:0;
overflow:hidden;
position: absolute;
top: -9999px;
}
Add the .shown class to your first fieldset.
You have no .next elements, but buttons named next.
So replace $(".next").click with $("button[name='next']").click.
Instead of if ($("#frmSignup").valid() == true), you can do if ($("#frmSignup").valid()).
And you'll need to remove the required attributes in your HTML, as hidden elements are not filled yet, so they prevent you from going to the next step. Let $.validate() do the job.
JS Fiddle Demo

How to validate only selected fields using parsley js

I'm using parsley js in two forms in a single page. i want to trigger parsley validator when i click on a type='button' field and validate the first form to check only 3 fields of the form. Initially there are around 7 fields in the form included for validation. So far I couldn't make it work. tried this but no luck.
any idea?
update: this is my code;
<div class = 'two'>
<input type='text' id='firstname' name='firstname' />
</div>
$('#form').parsley({
excluded: '.two input'
});
$('#form').parsley('validate');
i just tried to exclude one field and test if the form is validating as i want it to be. But still it validates input field inside css class 'two'. that's all i have done so far. no clue..
You have a couple of issues with your code, specifically with this line:
<dir classs = 'two'>
that should be
<div class = 'two'>
That is, you have dir instead of div and classs instead of class. You should also use $('#form').parsley().validate() instead of $('#form').parsley('validate').
The following code will work:
<form method='post' id='form'>
<div class = 'two'>
<input type='text' id='firstname' name='firstname' required />
</div>
<div>
<input type='text' id='thisisrequired' name='thisisrequired' required />
</div>
<button type="button" id="submit-form">Submit</button>
</form>
<script>
$(document).ready(function() {
$('#form').parsley({
excluded: '.two input'
});
$("#submit-form").on('click', function() {
$('#form').parsley().validate();
if ($('#form').parsley().isValid()) {
console.log('valid');
} else {
console.log('not valid');
}
});
});
</script>
You can view a more complete working example in this jsfiddle
For your case, you should consider using data-parsley-group (see the docs) to achieve the same result, with the following code:
<form method='post' id='form'>
<div>
<input type='text' id='firstname' name='firstname' data-parsley-group="first"
required />
</div>
<div>
<input type='text' id='thisisrequired' name='thisisrequired'
data-parsley-group="second" required />
</div>
<button type="button" id="submit-form">Submit</button>
</form>
<script>
$(document).ready(function() {
$('#form').parsley();
$("#submit-form").on('click', function() {
$('#form').parsley().validate("second");
if ($('#form').parsley().isValid()) {
console.log('valid');
} else {
console.log('not valid');
}
});
});
</script>
The difference between the two, is that in the first example you redefine the excludedoption. In the second example you would use data-parsley-group and validate only that group.
For a complete example, visit this jsfiddle (you can test it and change $('#form').parsley().validate("second"); to $('#form').parsley().validate("first"); to see what happens).
just an add on to the answer above, to work correctly ,
use group name in isValid too,ie $('#form').parsley().isValid("second")).
<script>
$(document).ready(function() {
$('#form').parsley();
$("#submit-form").on('click', function() {
$('#form').parsley().validate("second");
if ($('#form').parsley().isValid(**"second"**)) {
console.log('valid');
} else {
console.log('not valid');
}
});
});
</script>

Make hidden div and inputs optional for valid form submit with jquery.validate

I have a form that may only be one page or may be two pages depending on whether it is a single individual or two people applying. What I am doing right now is enabling a link that allows the user to get to the next group of form elements for their co-applicant via an onchange event that shows the link that will slideToggle the first users inputs and show the inputs for the additional users. It's a pretty lengthy form so I cut it down to a few elements so I could fiddle it out:
Das Fiddle is here
<form method="POST" id="refiLoanForm" action="mailto:i#i.com">
<!--START PRIMARY APPLICANT -->
<div id="primary-applicant">
<label>
Application Type
<select name="applicationType" id="applicationType" class="wider" required>
<option value="individual">Individual</option>
<option value="joint">Joint</option>
</select>
</label>
<br>
<label for="loan-amount" id="loan-amount-label">Requested Finance Amount
<input type="text" id="loan-amount" name="loanAmount" required/></label>
<br>
<label for="remaining-term">Current Loan Remaining Term
<input type="text" id="remaining-term" name="remainingTerm" max="3" size="3" required class="override"/>
</label>
<br>
CONTINUE TO CO-APPLICANT
</div>
<!--END PRIMARY APPLICANT -->
<!--START CO_APPLICANT -->
<div id="co-applicant" style="display: none">
Back to Primary Applicant
<br>
<label for="co-first-name">First Name
<input type="text" id="co-first-name" name="coApplicantGivenName" maxlength="32" required/>
</label>
<br>
<label for="co-last-name">Last Name
<input type="text" id="co-last-name" name="coApplicantFamilyName" maxlength="32" required/>
</label>
</div>
JS:
$('#refiLoanForm').validate({
onkeyup: false,
ignore: ":disabled",
submitHandler: function (form) { // for demo
alert('valid form');
return false;
}
});
$("#singleSubmitBtnLoan").bind('click', function () {
$('#refiLoanForm').valid();
});
//Handle the content being shown
$("#singleSubmitBtnLink2").on('click', function () {
$("#primary-applicant").slideToggle("slow");
$("#co-applicant").slideToggle("slow");
});
$("#backToPrimary").on('click', function () {
$("#primary-applicant").slideToggle("slow");
$("#co-applicant").slideToggle("slow");
});
$('#applicationType').on('change', function() {
if ($(this).val() === 'joint') {
$('.primaryApplicantSwitch').slideToggle("slow");
$('.jointApplicantSwitch').slideToggle("slow");
} else {
$('.primaryApplicantSwitch').slideToggle("slow");
$('.jointApplicantSwitch').slideToggle("slow");
}
});
So in theory, the user can enter the fields and hit submit and the form is either valid or throws some errors. Or, the user can add a co-applicant, and validate the form on the link click before toggling to the next group of inputs.
Any ideas on how I would bind all of this to the one button and get it to play nice with jquery.validate?
You cannot dynamically "toggle" the rules of input fields.
However, you can use the .rules() method to dynamically add/change/remove rules, which essentially mimics the behavior of a toggle.
Also, since you're talking about fields that are hidden, you'll need to disable the option that makes validation ignore all hidden fields.
ignore: []

Make a text entry fade out after input validation, then fade back in with original placeholder text

I'm setting up a splash page with a single email entry form.
Right now when a user enters an email the form fades out quickly and a thank you message fades in to replace it. What I want to do is have the 'Thank You' fade out after a couple of seconds then have the form fade back in.
I can get it to happen, it's just that the form comes back with the email that was originally entered and I'm having a hell of time trying to figure out a way of replacing the email address with the original placeholder text.
Here's the from:
<form action="" method="post" id="sendEmail">
<div class="forms">
<div class="buttons" id="buttons">
<button type="submit" id="submit"></button>
<input type="hidden" name="submitted" id="submitted" value="true"
/>
</div>
<div class="text_box" id="text_box">
<input type="text" name="emailTo" id="emailTo" value=" Your Email Here"
onfocus="this.value=''" />
</div>
</div>
</form>
<div class="answerBox">
<div style="display:none;" id="thanks">Thank you!</div>
</div>
And this is the Jquery I'm using to handle the fade in, fade out after successful validation:
if (hasError == false) {
$.post("adduser1.php", {
emailTo: emailToVal
}, function (data) {
$(".buttons").fadeOut(200);
$(".text_box").fadeOut(200, function () {
$("#thanks").fadeIn(200)
});
});
}
return false;
I tried this:
$.post("adduser1.php", {
emailTo: emailToVal
}, function (data) {
$(".buttons").fadeOut(200);
$(".text_box").fadeOut(200, function () {
$("#emailTo").text(" Your Email Here", function () {
$("#thanks").fadeIn(200))
});
But It doesn't work.
Any ideas?
First, #emailTo is not affected by .text as it's an <input> element. Replace .text with .val:
$("#emailTo").val(" Your Email Here")
Second, you're trying to bind #thanks.fadeIn to the end of .text (or .val) change. Since it's an instant action, this is unnecessary (and I think also not proper jQuery syntax). Just place $("#thanks").fadeIn(200) in the next line:
function (data) {
$(".buttons").fadeOut(200);
$(".text_box").fadeOut(200, function () {
$("#emailTo").val(" Your Email Here")
$("#thanks").fadeIn(200))
});
}
Working example: jsFiddle

Categories