I made a jQuery calculator that takes Fuel amount and Burn rate to give Time til empty to display on my screen. I also am using form validation.
When I click on the calculator button it runs form validation for some and tries to run the server-side code which is fine if I was clicking on the form submit button (and that button performs the way it should). But I have my calculator button "id" attribute and "name" attribute different than the form submit button. So I don't understand why when I click on the calculator button it tries to run form validation. In addition, it doesn't give me the total in the
$('#time-empty-field').val(time_empty);
field. Ideally, I want the calculator to show the total in the $('time-empty-field') and not run form validation.
I know my HTML is fine and from what I can see I don't see anything wrong with my jQuery. Maybe a different set of eyes can help on this. Any help would be much appreciated. Thanks!
$(function() {
$('#id').focus();
// To clear phone example when active
$('#phone').focus(function() {
var field = $(this);
if (field.val() == field.prop('defaultValue')) {
field.val('').css('color', 'black');
}
});
// Reveals System Report
$('#system-box input').click(function() {
if ($(this).attr('checked')) {
$('#system-report').slideDown('fast');
} else {
$('#system-report').slideUp('fast');
}
});
//Calculator
$('#calculator-submit-btn').submit(function() {
var fuel_amount = $('#fuel-amount-field').val();
var burn_rate = $('#burn-rate-field').val();
var time_empty = fuel_amount * burn_rate;
time_empty = time_empty.toFixed(2);
$('#time-empty-field').val(time_empty);
});
// Form validation plug-In
$('#form1').validate({
rules: {
id: {
required: true,
number: true
},
password: {
required: true
},
phone: {
required: true,
phoneUS: true
}
},
messages: {
id: {
required: "Please enter ID number."
},
password: {
required: "Please enter password."
},
phone: {
phoneUS: "Please enter a valid phone number."
}
}
});
});
$('#calculator-submit-btn').click(function() {
var fuel_amount = $('#fuel-amount-field').val();
var burn_rate = $('#burn-rate-field').val();
var time_empty = fuel_amount * burn_rate;
time_empty = time_empty.toFixed(2);
$('#time-empty-field').val(time_empty);
});
submit() can be used on submit forms only.
for more details chec jQuery API : http://api.jquery.com/submit/
Simply you cannot attach submit() event to a button , only to a form.
Related
Currently working on input file error validation When i searched about the validation i have found jquery validation so i have started using it and again when i searched about how to validate the input file i have got some useful information from SO Based on that I have created error validation page for input file. With my current code I can able to upload pdf & Jpeg file and view the file but the validation was not happening if user click next button without uploading any file it should say you have 2 files missed if the user upload one file and he click next button it should say you have 1 file miss. I have tried giving required in the html input type field and tried giving required in jquery validation nothing was working.
Here is my jquery code
$(".attachForm").validate({
ignore: false,
onkeyup: false,
showErrors: function (errorMap, errorList) {
var errors = this.numberOfInvalids();
if (errors) {
var message = errors === 0 ? 'You missed 1 field. It has been highlighted' : 'You have missed ' + errors + ' fields. Please fill before submitted.';
$("#error_message").html(message);
$(".error_msge").show();
} else {
$(".error_msge").hide();
}
this.defaultShowErrors();
},
errorPlacement: function () {
return false;
},
highlight: function (element) {
if($('input').attr('type') == 'checkbox') {
} else {
$(element).addClass('errRed');
$(".file_ipt").addClass('errRed');
}
$(element).prevAll('label').find('span.required-star').addClass('text-error-red').removeClass('text-error-black');
},
unhighlight: function (element) {
if($('input').attr('type') == 'checkbox') {
} else {
$(element).removeClass('errRed');
$(".file_ipt").addClass('errRed');
}
$(element).prevAll('label').find('span.required-star').addClass('text-error-black').removeClass('text-error-red');
},rules: {
apt_code:"required",
apt_cer:"required",
checkfile:"required"
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
I tried changing the name in all field but no use
Here is the fiddle link for the detailed code
Kindly please suggest me. kindly guide as i am not getting any stuff :(
Thanks for looking the question.
You have to assign the unique name attribute to each <input type="file" class="checkfile">
<input type="file" class="checkfile" name="file_alpha">
<input type="file" class="checkfile" name="file_beta">
and then in rules you have to define both fields and make sure they are required
rules: {
file_alpha: {
checkfile: "required",
required: true,
},
file_beta: {
checkfile: "required",
required: true,
}
},
Fiddle
Correct Solution
Above solution will work because assigning the unique name and required rules set will trigger the validation but will not return the desired result because OP trying to validate the input with same name attribute and triggering the error counter according to number of invalid input fields.
Reason the validation not working in original code because no required rules
rules: {
checkfile:"required"
},
defined anywhere.
so work around is set required rules and add to inputs with same name attribute OR type using jQuery each() function
$("input[type=file]").each(function() {
$(this).rules("add", {
required: true,
});
});
and validation will work, errors will triggered with counter and on validating the input field, error counter decrease as like OP's desired output.
Fiddle Proper Working Example
I have a form with fields which are pre populated with data from database, as I need to change phone number according to new data format schema, I also need to immediately fired up validation for pre populate input fieldd.
My JS code is as follows:
Method to validate HR phone numbers according to new schema:
$.validator.addMethod("mobileHR", function(phone_number, element) {
phone_number = phone_number.replace(/\(|\)|\s+|-/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^\+[0-9]{1,3}\.[0-9]{1,14}$/);
}, "Unesite broj u fromatu: +385.111234567");
And function calls:
$(document).ready(function () {
// initialize validation
$('.form-horizontal').validate({
// set immediate validation, on event code 9
onkeyup: function (element, event) {
if (event.which === 9 && this.elementValue(element) === "") {
return;
} else {
this.element(element);
}
},
rules: {
"contactdetails[Registrant][Phone]": {
required: true,
mobileHR: true
}
},
messages: {
"contactdetails[Registrant][Phone]": {
required: "Molimo unesite broj telefona"
}
}
});
});
Input field is like these, and value parameter is allready populated, as data is fetched from database.
<div class="controls">
<input kl_virtual_keyboard_secure_input="on" name="contactdetails[Registrant][Phone]" value="011123456" size="30" class="Registrantcustomwhois" type="text">
</div>
Now I want to warn a user editing data, even if he doesn't change data in desired input field, to update format of his phone number, so I basically want to call validate() function at the document has been loaded.
Fiddle with example is here.
after putting validation rules, on jQuery's ready, just add $('.form-horizontal').valid(); to validate form.
See Fiddle, updated accordingly
Sorry for keep asking this, but I just can't figure it out. I've reduced the question to just the bare minimum.
How can I validate a dynamically generated form? Below is my attempt, but as seen, it shows up as passing validation.
https://jsfiddle.net/j2pgobze/1/
<form id="myForm">
<input type="text" name="email" id="email" value="bademail" >
</form>
<button id="validate">validate</button>
var myValidateObj = {
rules: {
email: {
email: true
}
}
};
$(function () {
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$('#validate').click(function () {
//Validate the traditional form
var validate1 = $('#myForm').validate(myValidateObj);
console.log('Option 1', $('#myForm'), $('#email'), $('#email').val(), validate1.element('#email'), $('#email').valid(), $('#myForm').valid());
//Validate dynamically created form
var input = $('<input />', {
type: 'text',
name: 'email',
value: 'bademail'
});
//input.prop('value', 'bademail');
var form = $('<form />').append(input);
var validate = form.validate(myValidateObj);
console.log('Option 2', form, input, $('#email').val(), validate.element(input), input.valid(), form.valid());
});
});
The button needs to be inside the form and be a type="submit" in order for the plugin to capture the click.
Do not put .validate() within a click handler (See item 1). It's only used to initialize the plugin on a form. Exception, below we are creating the new form within a click handler and then immediately calling .validate() on the new form.
With these two small changes, the validation on the static form is working: jsfiddle.net/j2pgobze/3/
I rewrote your DOM manipulation code for clarity. I simply duplicated the HTML for the form and gave it a new ID: http://jsfiddle.net/zem84tfp/
$(function () {
// INITIALIZE plugin on the traditional form
var validate1 = $('#myForm').validate(myValidateObj);
$('#newform').one('click', function () {
// code here to create new form; give it new ID
// do not duplicate ID on anything else
// INITIALIZE plugin on the new form
var validate = $('#myForm2').validate(myValidateObj);
});
});
I am using Jquery with Validator plugin.
What I want to happen: When I popup a modal to edit a user I only want the password to be validated IF there is a password entered. I have this part covered. But if I begin to enter a password and then ultimately decide to erase it and move on it is still getting validated even though it is empty.
So if I never touch the password it doesn't get validated and this is what I want. If I do type and then remove what I typed it still tries to validate. This is not what I want. I want it to realize I decided against entering a new password for the user and again skip attempting to validate it.
$(document).ready(function() {
$("#epassword").focusout(function() {
if ($(this).val().length > 0) {
$("#editgirlform").validate({
rules: {
password: {
required: false,
pwcheck: true,
minlength: 6
}
},
messages: {
password: {
required: "Password required",
pwcheck: "Password must have at least 1 lowercase letter and 1 number!",
minlength: "The password must be at least 6 characters!"
}
}
});
}
});
$.validator.addMethod("pwcheck", function(value) {
return /^[A-Za-z0-9\d=!-#._]$/.test(value) // consists of only these
&& /[a-z]/.test(value) // has a lowercase letter
&& /\d/.test(value) // has a digit
});
}
I have a form with a required phone number field that looks like this with the maskedinput plugin
(999) 999-9999
I want the jquery validation to ignore the literals in order to validate this. Also, i want the literals to be removed before the form is submitted. But if there is a validation error i still want the maskedinput plugin activated so the format looks correct for the user still.
I figure i could edit the regex for the validation but then when the form is submitted the literals will still be on there.
Let me know i need to explain this better.
Any Ideas? I'm pretty new to jquery and all so detailed solution would be great.
My javascript code is this
$(document).ready(function(){
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "US Phone Number Required");
$("#valform").validate({
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
$("#error-message").show().text("Please correct the required field(s)");
} else {
$("#error-message").hide();
}
},
messages: {
phone: {
required: ""
}
},
rules: {
phone: {
required: true,
phoneUS: true
},
},
});
$("#phone").mask("(999) 999-9999",{placeholder:" "});
});
You could remove the other characters before submitting the form using js
This code will remove the forbidden character from the input as soon as its entered.
The input field has the class "numbers". This binds the "keyup" event to that input field and calls a function called "handleInputKeyUp"
$(".numbers").bind("keyup", handleInputKeyUp);
The function:
function handleInputKeyUp(e){
var temp = e.currentTarget.value;
temp = temp.replace(/[^\d-]/g, "");
e.currentTarget.value = temp;
}
This code removes all but digits and - from the input field.