I've got a form with a bunch of textboxes that are disabled by default, then enabled by use of a checkbox next to each one.
When enabled, the values in these textboxes are required to be a valid number, but when disabled they don't need a value (obviously). I'm using the jQuery Validation plugin to do this validation, but it doesn't seem to be doing what I expect.
When I click the checkbox and disable the textbox, I still get the invalid field error despite the depends clause I've added to the rules (see code below). Oddly, what actually happens is that the error message shows for a split second then goes away.
Here is a sample of the list of checkboxes & textboxes:
<ul id="ItemList">
<li>
<label for="OneSelected">One</label><input id="OneSelected" name="OneSelected" type="checkbox" value="true" />
<input name="OneSelected" type="hidden" value="false" />
<input disabled="disabled" id="OneValue" name="OneValue" type="text" />
</li>
<li>
<label for="TwoSelected">Two</label><input id="TwoSelected" name="TwoSelected" type="checkbox" value="true" />
<input name="TwoSelected" type="hidden" value="false" />
<input disabled="disabled" id="TwoValue" name="TwoValue" type="text" />
</li>
</ul>
And here is the jQuery code I'm using
//Wire up the click event on the checkbox
jQuery('#ItemList :checkbox').click(function(event) {
var textBox = jQuery(this).siblings(':text');
textBox.valid();
if (!jQuery(this).attr("checked")) {
textBox.attr('disabled', 'disabled');
textBox.val('');
} else {
textBox.removeAttr('disabled');
textBox[0].focus();
}
});
//Add the rules to each textbox
jQuery('#ItemList :text').each(function(e) {
jQuery(this).rules('add', {
required: {
depends: function(element) {
return jQuery(element).siblings(':checkbox').attr('checked');
}
},
number: {
depends: function(element) {
return jQuery(element).siblings(':checkbox').attr('checked');
}
}
});
});
Ignore the hidden field in each li it's there because I'm using asp.net MVC's Html.Checkbox method.
Using the "ignore" option (http://docs.jquery.com/Plugins/Validation/validate#toptions) might be the easiest way for you to deal with this. Depends on what else you have on the form. For i.e. you wouldn't filter on disabled items if you had other controls that were disabled but you still needed to validate for some reason. However, if that route doesn't work, using an additional class to filter on (adding and removing with your checkboxes) should get you to where you want to go, but easier.
I.e.
$('form').validate({
ignore: ":disabled",
...
});
Usually when doing this, I skip 'depends' and just use the required jQuery Validate rule and let it handle the checking based on the given selector, as opposed to splitting the logic between the validate rules and the checkbox click handler. I put together a quick demo of how I accomplish this, using your markup.
Really, it boils down to required:'#OneSelected:checked'. This makes the field in question required only if the expression is true. In the demo, if you submit the page right away, it works, but as you check boxes, the form is unable to submit until the checked fields are filled with some input. You could still put a .valid() call in the checkbox click handler if you want the entire form to validate upon click.
(Also, I shortened up your checkbox toggling a bit, making use of jQuery's wonderful chaining feature, though your "caching" to textBox is just as effective.)
Depends parameter is not working correctly, I suppose documentation is out of date.
I managed to get this working like this:
required : function(){ return $("#register").hasClass("open")}
Following #Collin Allen answer:
The problem is that if you uncheck a checkbox when it's error message is visible, the error message doesn't go away.
I have solved it by removing the error message when disabling the field.
Take Collin's demo and make the following changes to the enable/disable process:
jQuery('#ItemList :checkbox').click(function()
{
var jqTxb = $(this).siblings(':text')
if ($(this).attr('checked'))
{
jqTxb.removeAttr('disabled').focus();
}
else
{
jqTxb.attr('disabled', 'disabled').val('');
var obj = getErrorMsgObj(jqTxb, "");
jqTxb.closest("form").validate().showErrors(obj);
}
});
function getErrorMsgObj(jqField, msg)
{
var obj = {};
var nameOfField = jqField.attr("name");
obj[nameOfField] = msg;
return obj;
}
You can see I guts remove the error message from the field when disabling it
And if you are worrying about $("form").validate(), Don't!
It doesn't revalidate the form it just returns the API object of the jQuery validation.
I don't know if this is what you were going for... but wouldn't changing .required to .wasReq (as a placeholder to differentiate this from one which maybe wouldn't be required) on checking the box do the same thing? If it's not checked, the field isn't required--you could also removeClass(number) to eliminate the error there.
To the best of my knowledge, even if a field is disabled, rules applied to it are still, well, applied. Alternatively, you could always try this...
// Removes all values from disabled fields upon submit
$(form).submit(function() {
$(input[type=text][disabled=disabled]).val();
});
I havent tried the validator plugin, but the fact that the message shows for a splitsecond sounds to me like a double bind, how do you call your binders? If you bind in a function try unbinding just before you start, like so:
$('#ItemList :checkbox').unbind("click");
...Rest of code here...
Shouldn't validate the field after disabling/enabling?
jQuery('#ItemList :checkbox').click(function(event) {
var textBox = jQuery(this).siblings(':text');
if (!jQuery(this).attr("checked")) {
textBox.attr('disabled', 'disabled');
textBox.val('');
} else {
textBox.removeAttr('disabled');
textBox[0].focus();
}
textBox.valid();
});
I had the exact same problem.
I solved this by having the radio-button change event handler call valid() on the entire form.
Worked perfect. The other solutions above didn't work for me.
Related
I'm using genvalidator to have some tests on input fields in a form. Problem is I can't find a way to test if a checkbox has been checked. This is how all the fields are set:
frmvalidator.addValidation("name","req","Insert your name");
frmvalidator.addValidation("city","req","Insert your city");
frmvalidator.addValidation("phone","req","Insert your phone number");
This is my checkbox
<input type="checkbox" name="agree" id="agree "value="yes"/>
How can I make it mandatory with genvalidator?
This is the part that handles the form process (in short: if there aren't errors, it's ok):
if(empty($name)||empty($city)||empty($phone)||BLAHBLAH)
{
$errors .= "\n Mandatory field. ";
}
if(empty($errors))
{
// send the email
}
It tried with this JS code with no luck:
function validate(form) {
if(!document.form1.agree.checked){alert("Please check the terms and conditions");
return false; }
return true;
}
If possible I'd like to use genvalidator functions. :)
You are expending a lot of energy trying to make the javascript plugin work.
Would you consider working with jQuery? If you haven't yet kicked its tires, it's a lot easier than it sounds -- and much more uniform / faster to type than plain js.
To use jQuery, you only need to include the jQuery library in the document, usually in the head tags thus:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
Then, you can easily create you own verification routines, with FULL control over what you are doing.
Here is a working example for you to study. As you can see, the code is pretty minimal.
When the Submit button (#mysub) is clicked, we quickly check each field to see if it validates. If any field fails validation, we can return control to the user with the field colored and in focus.
If all fields pass validation, then we issue the submit() method on the form ID, and off it goes (to the location specified in the action="somepage.php" attribute).
Note that I added some quick/dirty code at bottom to remove any css colorization from failed validations. This code runs every time a field is exited, regardless whether the field has validation coloring or not. This is not very efficient (although it certainly won't hurt anything) and is only intended to demonstrate what is possible.
Hmmmmm. I think it would be more efficient to have a class with certain attributes, and add/remove that class if fail validation. Okay, I liked that idea enough that I created a new jsFiddle using that method to demonstrate what that would look like.
jsFiddle here
HTML:
<form id="fredform">
First Name: <input id="fname" name="fname" type="text"/>
Last Name: <input id="fname" name="fname" type="text"/>
Email: <input id="fname" name="fname" type="text"/>
<input id="mysub" type="button" value="Submit" />
</form>
jQuery:
arrValidate = ['fname','lname','email']
$('#mysub').click(function() {
var nextFld, i ;
for (i=0; i<arrValidate.length; i++){
nextFld = arrValidate[i];
if ( $('#'+nextFld).val() == '') {
alert('Please complete all fields. You missed the [' +nextFld+ '] field.');
$('#'+nextFld).css({'border':'1px solid red','background':'yellow'});
$('#'+nextFld).focus();
return false;
}
}
//if it gets here, all is okay: submit!
$('#fredform').submit();
});
//Remove any css validation coloring
$('input:not([type=button])').blur(function(){
$(this).css({'border':'1px solid lightgrey','background':'white'});
});
Note that there is also a jQuery validation plugin that looks very professional. I haven't played with it myself, always preferring to code my own stuff, but here is the link:
http://jqueryvalidation.org/documentation/
Note the very cool demo
Just so you know what to expect: implementing this plugin would be more difficult than the methodology I suggested above.
` ANSWER TO YOUR COMMENT QUESTION: `
Regarding your comment and the code posted at pastebin:
(Sorry for the long answer, but I want it to be clear. Please read carefully.)
(1) Please wrap your javascript code in a document.ready function. This is my fault; I should have added it to my code example. Otherwise, the code will execute before the DOM fully exists and event triggers will not be bound to the controls (because they do not yet exist in the DOM). Therefore:
arrValidate = ['checkbox']; //a global variable
$(document).ready(function() {
$('#submit').click(function() {
var nextFld, i ;
for (i=0; i<arrValidate.length; i++){
nextFld = arrValidate[i];
if ( $('#'+nextFld).val() == '') {
alert('Please complete all fields. You missed [' +nextFld+ ']');
$('#'+nextFld).css({'border':'1px solid red','background':'yellow'});
$('#'+nextFld).focus();
return false;
}
}
//if it gets here, all is okay: submit!
$('#contact_form').submit();
}); //END #submit.click
}); //END document.ready
(2) Your checkbox still has the value="yes" attribute that breaks the javascript. Please change this:
<input type="checkbox" name="checkbox" id="checkbox" value="yes" /> <small>Ho
to this:
<input type="checkbox" name="checkbox" id="checkbox" /> <small>Ho
(3) There is no need to have type="submit" for your <input value="Invia"> button, nor is there a need for a name= attribute on that control.
First the name= attribute: it is only useful when passing data from that control to the PHP(?) file that processes your form: ($_SERVER['SCRIPT_NAME']). The name= part is the variable name, and the value of the control is the variable value. The button has no data to pass along, so does not need to have a variable name assigned to it.
Next, the type="submit": This is not required, because you can use jQuery to submit the form any time you want. In the old days, before javascript/jQuery, we had forms. Back in those days, the only way to make the form submit was to use the type="submit" attribute. There was no such command as: $('#myFormId').submit(); -- but today there is. So change that attribute to type="button" and let jQuery submit the form for you. Trust me, this works!
Another thing to consider: once you use type="submit" you must deal with the form's default actions when clicking that button. You cannot simply return control to the user when there is an error, because the form has been told to submit. (You must use event.preventDefault() to override the default behaviour -- you can read about that later.)
(4) Checkbox values must be checked using one of these methods. Checkboxes do not have a value. This is my fault again, I should have written a checkbox into my example.
$('#submit').click(function() {
var nextFld, i ;
//Validate the checkbox:
if ( $('#checkbox').is(':checked') == false ) {
alert('You must read the informativa and check the checkbox at bottom of form');
return false;
}
//Validate the rest of the fields
for (i=0; i<arrValidate.length; i++){
(5) jQuery's submit() method won't work IF any element uses =submit as either its name= or id= attribute.
This is a weird thing, but you need to know it. I just learned it (again) while troubleshooting my jsFiddle example.
If you want to use jQuery to submit your form (and we do) via the .submit() method, then no element in your form can have the name= or id= attribute set to "submit". The INPUT button had both name= and id= set to submit; that is why it wasn't working.
Reference: http://blog.sourcecoder.net/2009/10/jquery-submit-on-form-element-does-not-work/
See the revised code example in the jsFiddle:
Revised jsFiddle here
Please Please Please study the above jsFiddle. You should be able to dump the genvalidator plugin entirely. If you understand the jsFiddle completely, you will be in a new place as a programmer.
If you're using jQuery, try checking this way:
function validate(form) {
if(!$('[name="agree"]').prop('checked')){
alert("Please check the terms and conditions");
return false;
}
return true;
}
or try using
function validate(form) {
if(!$('[name="agree"]')[0].checked){
alert("Please check the terms and conditions");
return false;
}
return true;
}
This is untested but I think it would look something like this:
function DoCustomValidation() {
var frm = document.forms["myform"];
if(document.form1.agree.checked != true) {
sfm_show_error_msg('The Password and verified password does not match!',frm.pwd1);
return false;
}else{
return true;
}
}
Note that you must customize this line to have the correct name of your own form:
var frm = document.forms["myform"];
Plus, you also need to associate the validation function with the validator object:
frmvalidator.setAddnlValidationFunction("DoCustomValidation");
Source: genvalidator documentation
Since you've tagged the question with JQuery, this should work for you:
function validate(form) {
if ($("#agree :checked").length < 1) {
alert("Please check the terms and conditions");
return false;
}
return true;
}
I tend to use this approach because it also works for multiple checkboxes or radio button groups as well. Note, however, that it does not care about what was checked, just that something was checked . . . in the case of a single checkbox, this acts as a "required to be checked" validation as well.
Add a new div for error location above your input tag like this :
<div name="formname_inputname_errorloc" class="errorstring">
//<your input tag goes here>
Make sure u have the css for errorstring class in your css file. and the other req js files
Try to search the demo for gen validator it has been totally explained in the demo
frmvalidator.addValidation("agree","selmin=1","Please select checkbox");
I'm using the Foundation 4 framework and I added a custom form into my page.
HTML:
<label for="checkbox2">
<input type="checkbox" id="checkbox2" style="display: none;">
<span class="custom checkbox"></span> <p> CHECKBOX TEST</p>
</label>
JS:
if($('#checkbox2').is(":checked")){
isnewsletter = 1;
} else {
isnewsletter = 0;
}
and even this
newsletter = $('#checkbox2').val(),
isn't working.
How can I check, if my checkbox is checked?
$('#checkbox2').change(function(){
if($(this).is(":checked")){
console.log(1);
} else {
console.log(0);
}
});
First checking works fine. If you add checked="checked" to your checkbox isnewsletter will be 1.
P.S. You don't mention any other way how you tick checkbox in your program. Your checkbox is not displayed on the page, so you cannot tick it manually.
The question isn't quite clear whether OP wants to check if checkbox is :checked on change, at any random moment during interaction on a page, or on validation using the Foundation 4 Abide library. I've run into issues with the custom form and toggling hidden fields, as well as validating hidden fields, and the custom form doesn't help. However, I've worked around it, but those are different questions.
The "custom" form does by default hide the input and create a span after it that gets the class "checked", and the property on the hidden checkbox doesn't visually appear in Chrome's developer toolbar (I haven't checked FireBug to see if that property appears). However, if you write a code based check of the property of the checkbox, it will return 'true':
$("#checkbox2").change(function() {
console.log($(this).is(":checked"));
console.log($(this).prop('checked'));
// set up if using either method above, your choice.
if( $(this).prop('checked')) {
// do stuff
}
});
Or you can check the span.checkbox.custom directly after the input for the class "checked":
$("#checkbox2").change(function() {
console.log($(this).next().hasClass("checked"));
// set up if statement using that logic above:
if($(this).next().hasClass("checked") ) {
// do stuff
}
});
Use the same logic to check whether the checkbox is checked at any point, just don't bother with the .change() function. These will return true if the box is checked:
$("#checkbox2").next().hasClass("checked");
$("#checkbox2").is(":checked");
$("#checkbox2").prop("checked");
Foundation 4 didn't have validation built into Abide, you'd have to add it in.
This requires adjusting Abide.
I answered that question here.
I have an input field called email class keyup-an. I validate it easy with this, but it works or when an individual inputs the field manually. How do i make it work also for selecting historical data. when you click email and yesterday you put test#test.com, the history list drops down and you can select it, but its not a keyup.
I TRIED the same function after but with .change or .click and it didnt work. Can you guys please suggest?VALID
$('.keyup-an').keyup(function() {
$('span.error-keyup-1').hide();
var inputVal = $(this).val();
var numericReg = /^[a-zA-Z0-9_ ]{2,30}$/;
if(!numericReg.test(inputVal)) {
$(this).css('background', '#FAC3C3');
$(this).after('<span class="error error-keyup-1">Validationfail</span>');
}
else {
$(this).css('background', 'lightgreen');
}
});
you can do this by
autocomplete='off'
example
<form name="form1" id="form1" method="post" autocomplete="off">
or try something like
$(input).autocomplete().keyup(function(event) {
event.stopPropagation();
}).keydown(function() {
$(this).autocomplete('search', $(input).val());
});
good read
How to Turn Off Form Autocompletion
If I understand you correctly, you want an event which gets triggered if you click on the autocomplete item.
This is a known bug, check out this article about a jquery plugin, I think this is exactly what you need:
http://furrybrains.com/2009/01/02/capturing-autofill-as-a-change-event/
Instead of binding your function to the keyup event.. maybe bind it to change event?
ok.. this doesn't work on some browsers it seems.. you can refer to the previous answer and use the solution, which basically creates a timer to check the values in intervals to detect changes. Forcing the browser to do a lot of work if you want the validation to happen very fast imo.. Or you could turn of autocomplete and force the user to enter the values manually like the first answer suggested.
I have a form being validated by jQuery.validate. Using errorPlacement option I have a custom set of functions for real-time error validation. Using success option I have a custom set of functions to get rid of and replace error messages.
All works great except my validation on hidden fields only works on submit. With the success option the jQuery.validate is performing perfectly for all other fields except for my hidden fields. I'm using hidden fields to consolidate values from multiple text boxes and check boxes. Here's an example on my dilemma with three birthdate fields: day, month, year:
The HTML:
<label for="birthmonth">Birthdate</label></div>
<div class="birthfield1"><input type="text" id="birthmonth" name="birthmonth" class="ignore" /></div>
<div class="birthfield23"><input type="text" id="birthday" name="birthday" class="ignore" /></div>
<div class="birthfield23"><input type="text" id="birthyear" name="birthyear" class="ignore" /></div>
<div class="errorparent"><input id="birthdate" name="birthdate" type="hidden" /><div class="norederrorx errordetails2"> </div></div>
The jQuery/javascript to update the hidden birthdate field:
$('#birthday,#birthmonth,#birthyear').change(function() {
var inputbirthday = $('#birthday').val();
var inputbirthmonth = $('#birthmonth').val();
var inputbirthyear = $('#birthyear').val();
if (inputbirthday && inputbirthmonth && inputbirthyear) {
alert('all values');
$('#birthdate').val($('#birthday').val()+'/'+ $('#birthmonth').val()+'/'+ $('#birthyear').val());
}
if (inputbirthday == "" || inputbirthmonth == "" || inputbirthyear == ""){
$('#birthdate').val('');
}
});
And the jQuery.validate success option code (which works:
success: function() {
if (elementholder.hasClass('ignore') == false) {
errorspotholder.find('.rederrorx').removeClass('rederrorx').addClass('norederrorx');
}
},
My use case is a bit different in that I don't use a custom handler for success. However, I was having an issue where the error wouldn't disappear after the hidden field was changed. What I'm saying is that I'm using the default error and success functionality, but there shouldn't be any difference -- your handler should still get run.
It seems the easiest way to handle this is to call the .form() method. So, within the event that fills (or empties) the hidden input, I simply have this:
input.parents('form').validate().form();
input being the $()-ized element from the event, then I traverse upward to get the form (which the validator was attached to), then the validator, then call .form(). This retests the form, clears/adds errors where applicable, but doesn't submit.
Hope that helps,
James
Okay...no answer on this one...
But I'm pretty sure it's a missing feature of jQuery.validate (that changes in hidden fields don't fire success and errorPlacement events). I got around it by replicating the code under success and errorPlacement inside of jQuery change events, like so:
$('#chboxterms').change(function() {
if ($('#chboxterms').is(':checked')) {
//replicate jQuery.validate "success" code here
} else {
//replicate jQuery.validate "errorPlacement" code here
}
}
If you are using dynamic events and error messages, which you probably are...you'll have to replace that code with the static alternative that relates to the $('selector') that you're coding for.
Hope that helps someone!
In my example below I'm using a dijit.form.DateTextBox:
<input type="text" name="startDate" dojoType="dijit.form.DateTextBox" constraints="{datePattern:'MM/dd/yyyy'}" value='<c:out value="${sessionScope.adminMessageForm.startDate}"/>' />
So for example, if the user starts to enter "asdf" into the date the field turns yellow and a popup error message appears saying The value entered is not valid.. Even if I remove the constraints="{datePattern:'MM/dd/yyyy'}" it still validates.
Without going into details as to why, I would like to be able keep the dojoType and still prevent validation in particular circumstances.
Try overriding the validate method in your markup.
This will work (just tested):
<input type="text" name="startDate" dojoType="dijit.form.DateTextBox"
constraints="{datePattern:'MM/dd/yyyy'}"
value='<c:out value="${sessionScope.adminMessageForm.startDate}"/>'
validate='return true;'
/>
My only suggestion is to programmatically remove the dojoType on the server-side or client-side. It is not possible to keep the dojoType and not have it validate. Unless you create your own type that has you logic in it.
I had a similar problem, where the ValidationTextBox met all my needs but it was necessary to disable the validation routines until after the user had first pressed Submit.
My solution was to clone this into a ValidationConditionalTextBox with a couple new methods:
enableValidator:function() {
this.validatorOn = true;
},
disableValidator: function() {
this.validatorOn = false;
},
Then -- in the validator:function() I added a single check:
if (this.validatorOn)
{ ... }
Fairly straightforward, my default value for validatorOn is false (this appears right at the top of the javascript). When my form submits, simply call enableValidator(). You can view the full JavaScript here:
http://lilawnsprinklers.com/js/dijit/form/ValidationTextBox.js