I'm working on a web form where I wish to (after form submission) highlight those input fields that weren't entered correctly.
The highlight effect I wish to create is an endlessly looping animation between background-color: #fcc; and #fff; in the faulty input fields, using jQuery. When one of those fields gain focus, I wish to stop the animation of that field.
I'm fairly off-beat in jQuery and JS, so if anyone could point me in the right direction, I'd be sincerely grateful.
Check out these two jQuery plugins:
Pulse: http://james.padolsey.com/javascript/simple-pulse-plugin-for-jquery/
Seek Attention: http://enhance.qd-creative.co.uk/demo/seekAttention/ (link now dead)
I think Pulse is what you were asking for, but Seek Attention could be useful in some cases as well.
Here is a very rudimentary sample I created using the pulse plug in.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" type="text/javascript"></script>
<script src="http://enhance.qd-creative.co.uk/demos/pulse/pulse.jquery.js" type="text/javascript"></script>
<script type="text/javascript">
function doSomething() {
if ($('.BadTextBox').val() == "") {
$('.BadTextBox').pulse({ backgroundColors: ['#fcc', '#fff'] });
}
else {
$('.BadTextBox').css({'background-color': '#fff'}).stop();
}
}
</script>
<input type="text" class="BadTextBox" onblur="doSomething();" />
When the user navigates away from the text box it starts pulsing if empty. If they go back and fill it out, it stops pulsing.
I did something similar
Firstly create the javascript function variable
var PulsePut = function (){
if ($(this).val() == "") {
$(this).pulse({ backgroundColors: ['#ffffee', '#fff'] });
}
else {
$(this).css({'background-color': '#fff'}).stop();
} }
Then add a class to the inputs
<input type="text" class="PulsePut" />
Finally, to initialise the function
$(document).ready(function(){
$('.PulsePut').blur(PulsePut); }
This will make any input you have with the class .PulsePut pulse if empty.
here's how i would do it (general steps):
loop through inputs, add class "incorrect" to those fields
while looping, toggle bg of "incorrect" classes, sleep for however long
on click of input, remove it's "incorrect" class.
this may not work if in the while loop, nothing else is executable. post fixes in the comments.
I would capture the onblur event and trigger a function to validate the input:
function matchShippingEmail() {
$('#shippingEmail').css('border',validColor);
if ($('#shippingEmail').val() == '') {
$('#shippingEmailLabel').html('email');
return 0;
}
if ($('#shippingEmail').val().match(RegExp('^([a-zA-Z0-9._%%-]+#+[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})'))) {
$('#shippingEmailLabel').html('email');
return 1;
} else {
$('#shippingEmail').css('border',invalidColor);
$('#shippingEmailLabel').html(email error');
return 0;
}
}
On form submission, I did this:
$(document).ready(function() {
$('.confirmOrder').click(function(event){
if (!matchCardOwnerName()) {$('#cardOwnerName').css('border',invalidColor); $('#cardOwnerName').focus(); return false;}
if (!matchCardNumber()) {$('#cardNumber').css('border',invalidColor); $('#cardNumber').focus(); return false;}
if (!matchCVV2Code()) {$('#CVV2Code').css('border',invalidColor); $('#CVV2Code').focus(); return false;}
if (!matchCardOwnerId()) {$('#cardOwnerId').css('border',invalidColor); $('#cardOwnerId').focus(); return false;}
if (!matchShippingFullName()) {$('#shippingFullName').css('border',invalidColor); $('#shippingFullName').focus(); return false;}
if (!matchShippingAddress()) {$('#shippingAddress').css('border',invalidColor); $('#shippingAddress').focus(); return false;}
if (!matchShippingCity()) {$('#shippingCity').css('border',invalidColor); $('#shippingCity').focus(); return false;}
if (!matchShippingZipCode()) {$('#shippingZipCode').css('border',invalidColor); $('#shippingZipCode').focus(); return false;}
if (!matchShippingEmail()) {$('#shippingEmail').css('border',invalidColor); $('#shippingEmail').focus(); return false;}
if (!matchShippingPhoneNumber()){$('#shippingPhoneNumber').css('border',invalidColor); $('#shippingPhoneNumber').focus(); return false;}
if (!$('#agreeToTermsAndConditions').attr('checked')) {
$('#agreeToTermsAndConditionsDiv').css('color','#FF0000');
$('#agreeToTermsAndConditionsDiv').css('font-weight','bold');
$('#agreeToTermsAndConditionsDiv').css('font','150%% ariel');
return false;
}
$('html').css('cursor','wait');
$('.confirmOrder').css('cursor','wait');
$('#confirmOrderButton').attr('src','images/confirmOrderDisabled.jpg');
$('#paymentForm').submit();
//document.paymentForm.submit();
$('form').get(0).setAttribute('action', '#'); //this works
return true;
});
});
Related
I'm having an issue with my validation process. I'm not using a standard "submit" button, rather I have <span class="button" id="print">Print</span> and jQuery listens for a click. This is the validation code I have when that "button" is clicked:
var validation = "";
function validate() {
$("#servDetails").find("input").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
$("#checklist").find("input[required]").each(function () {
if ($(this).prop("required") && $(this).val() == "") {
validation = false;
}
else {
validation = true;
}
});
}
$("#print").on("click", function() {
validate();
if (validation == false) {
alert("Please fill out all required inputs!");
return false;
}
else {
window.print();
}
});
If I click the button without filling anything out (all items blank), I get my alert as expected.
If I fill out all of the required elements, it pulls up the print dialouge as expected.
However, if I leave some of the boxes blank while others are correctly filled, it still goes to print instead of giving me the alert like I need. Any thoughts?
The code have to be rewritten, or better replace it with any validation plug-in.
But in your case, I suppose, you just forgot to return, in case you found some not filled field. So if you have any filled input it override your validation variable.
The simplest solution is to remove
else {validation = true;} code blocks, and add
validation = true;
at the beggining of the function.
Friends i am new to javascript, I am trying to write a script to validate the entire form whenever any input field value is changed of input fiels with the data attribute of required.
HTML
<form>
<input type="text" name="FirstName" class="inputField" data-required="true"></input>
<input type="text" name="MiddleName" class="inputField"></input>
<input type="text" name="LastName" class="inputField" data-required="true"></input>
</form>
SCRIPT
var field, required, isValid, fieldVal;
function validatedForm() {
field = document.querySelectorAll('.inputField');
document.getElementById("submitButton").disabled = true;
var isValid = true;
for(var i=0; i < field.length; i++){
required = field[i].dataset.required;
if(required){
field[i].addEventListener('blur', function(e){
fieldVal = this.value;
if(fieldVal == ''){
isValid = false;
}
checkSubmitBtn();
}, true);
}
}
function checkSubmitBtn() {
if(isValid = true) {
console.log(isValid);
document.getElementById("submitButton").disabled = false;
}
}
}
window.addEventListener("load", validatedForm);
PROBLEM 1:
The isValid is not updating hence even an empty blur on the input field makes the button disable to be false.
PROBLEM 2:
In case there are multiple forms on the page then how to validate only the desired forms .. just like in jQuery we add a script tag in the end to initialize the script according to it.
PROBLEM 3:
Is there a way to change the disable state of the button without the GetElementID ... I mean if that can be managed depending on the submit button of that particular form on the page where the script is suppose to work.
Any help will be highly appreciated. Thanks in advance.
I think you need something like the following form validation..
<script type="text/javascript">
var field, fieldVal, required = false;
function validatedForm() {
field = document.querySelectorAll('.inputField');
document.getElementById("submitButton").disabled = true;
field.forEach(function(elem) {
required = elem.dataset.required;
if(required){
elem.addEventListener('blur', function(e) {
checkSubmitBtn(field);
});
}
});
}
function checkSubmitBtn(field) {
var isDisabled = false;
field.forEach(function(elem) {
fieldVal = elem.value.trim();
if(fieldVal == ''){
isDisabled = true;
return false;
}
});
document.getElementById("submitButton").disabled = isDisabled;
}
window.addEventListener("load", validatedForm);
</script>
I hope it helps...
There are quite a few things going on here. First, your checkSubmitBtn function used a single = operator in the if statement. This won't actually check the variable, it instead will set the variable to that value. Here is the fixed function:
function checkSubmitBtn() {
if (isValid == true) {
document.getElementById("submitButton").disabled = false;
}
}
You mentioned not wanting to use getElementById. There are a few ways around this. One way would be to call the function once and store it in a variable to use later, like so:
var button = document.getElementById("submitButton");
...
function checkSubmitBtn() {
button.disabled = !isValid;
}
Another way would be to use jQuery. It still is technically calling getElementById in the backend, but the code is much simpler. If you wanted to avoid that, you also can still combine this with the technique I described above.
$("#submitButton").attr("disabled", !isValid);
I'd also like to point out that your code doesn't account for a situation where a form goes from invalid (starting point) to valid and back to invalid again. Say a user types in all of the fields but then backspaces everything. Your code will fall apart.
Lastly, your <input> HTML tags should not be closed. There are certain tags that are considered "self-closing", i.e. you don't have to write the closing tag, </input>.
I have two buttons in my html page and when someone clicks Generate button I want to save my document (the same thing save button is doing) if ok is clicked otherwise I do not want to do anything.
Js code
$("#save-application").trigger("click");
I also tried to use
document.getElementById('save-application').click();
and
$('#save-application').click();
But it isnt working.So basically I want to call my save button.Any suggestions on this?
I did tried
if (check == true) {
$("#form").submit();
return true;
}
else {
return false;
}
but form doesn't get saved
I think you missed # while querying by id $("#save-application").click();.
Instead of using trigger , you can create separate function for save functionality,
html code :
<input type="submit" value="Save" id="save-application" onclick="saveApplication();"/>
js code :
function saveApplication(){
//logic here
}
and then call saveApplication() instead of $("save-application").trigger("click");
So I'd do something like this on your input
<input id="save-application" type="submit" value="Save" onclick="saveApplication()"/>
Then modify your javascript to something like this:
function saveApplication() {
if (isChanged == true ) {
var check = confirm("Would you like to to save your changes and have a document generated?");
if (check == true) {
$("#save-application").trigger("click");
return true;
}
else { return false; }
} else {
return undefined;
}
}
Hope this helps
Hi all im new to jscipt,,, well, programming in general to be honest, but learning slowly for personal use.
I seek guidence on how i could place all the textboxes(inputs) in my index file into a list container, loop through them to check if they are empty or not before clicking the calculate button. If they are empty then inform the user of which one is empty.
Also, is there a way of preventing users from entering text into the textboxes and numbers only.
Background: im creating a form that requires all fields to be populate with numbers(in hours), a graph will then be generated from those values.
ive placed the file in skydrive for folks to download with the link below.
Index file
I did try the following but this alerts me regardless of weather the texboxes are populate or not.
function checkInputsGenerateGraph()
{
if( $('#hutz-hoursInput').val() == ""||$('#hutz-weeksPerYearInput').val() == ""||$('#hutz-jobsPerWeekInput').val() == ""||$('#hutz-hourlyMachineRateInput').val() == ""||$('#hutz-maintneneceDowntimeInput').val() == ""||$('#hutz-scrapRateInput').val() == ""||$('#hutz-toolsPerJobInput').val() == ""||$('#hutz-timeToLoadToolInput').val() == ""||$('#hutz-timeToSetPartsInput').val() == "")
{
alert('One them is empty!!');
}
else
{
$("#hutz-graph").slideDown();
$("#hutz-lblImproveMyProcess").slideUp();
$("#hutz-hoursInput").slideUp();
$("#hutz-weeksPerYearInput").slideUp();
$("#hutz-jobsPerWeekInput").slideUp();
$("#hutz-ourlyMachineRateInput").slideUp();
$("#hutz-ntneneceDowntimeInput").slideUp();
$("#hutz-scrapRateInput").slideUp();
$("#hutz-toolsPerJobInput").slideUp();
$("#hutz-timeToLoadToolInput").slideUp();
$("#hutz-timeToSetPartsInput").slideUp();
$("#hutz-lblMachineDetails").slideUp();
$("#hutz-lblPartSetting").slideUp();
$("#hutzcurrencyPreferenceInput").slideUp();
createChart();
}
}
First off, give all the required elements a common class, for examples sake we'll call this required:
<input type="text" class="required" id="hutz-hoursInput" />
Then, when your checkInputsGenerateGraph() function is called, you can loop over the required elements and check them:
$('.required').each(function() {
if (this.value.length == 0) {
alert(this.id + ' is empty!');
}
});
You could also do something like the following to remove all non-digits from your inputs:
$('.required').change(function() {
this.value = this.value.replace(/[^\d]+/, '');
});
See it in action
Hope that points you in the right direction!
edit
Here's a complete example:-
function checkInputsGenerateGraph() {
var isValid = true;
$('.example').each(function() {
if (this.value.length == 0) {
alert(this.id + ' is empty!');
isValid = false;
}
});
if (isValid) {
alert('do calculations!');
}
}
So, loop over all of the elements first, and make sure they are all populated. If not, set isValid to false so that once the loop completes, the calculations are not performed.
I'm having trouble getting the validation function results "Required field" to fill the text input box of a table.
The current code is placing the result to the right of the cell instead of inside.
I'm fairly positive it's the $(this).parent().append portion but after trying several other variations I haven't achieved the expected results.
*The code verifies that a value is currently in the cell by means of examining the class = requiredField attribute.
Any tips are much appreciated. -Thank you.
<script type="text/javascript">
$(document).ready(function() {
$('form#commentform').submit(function() {
$('form#commentform .error').remove();
var hasError = false;
$('.requiredField').each(function() {
if(jQuery.trim($(this).val()) == '') {
$(this).parent().append('<span class="error">*Required field</span>');
hasError = true;
}
});
if(!hasError) {
alert('Validation Complete');
}
return false;
});
});
</script>
You can use the after() method:
$(this).after('<span class="error">*Required field</span>');
http://api.jquery.com/after/