I have multiple DIV's on a page,which contain form fields.Some of them are required and some not.When a user jumps from one div to other by entering data.I have to validate the required fields are satisfied and change the CSS of that completed DIV.If required fields are not met,i should not change the css effect.I would like to approach this with Jquery.So,Can someone provide a good and clean design to approach.
Thanks
You can use jQuery validator
plugin for validating your content.
Once your div looses focus you can then check if validation has passed or not, if not then dont apply the css or else apply css.
Sample code:
$("#divid").validate({
onfocusout: false, //once div looses focus validate
rules: {
//your rules go here
}
});
Take a look at the jquery validate plugin
Using jQuery validation you can create your own method to validate a group of controls, I use this approach to wrap elements in a div or fieldset with the class name "validationGroup". Then, when I trigger an event from within the group I navigate up the DOM to the parent element with the class name and validate everything underneath. Using this approach, you can control/limit the validation to the controls in the current div being edited.
function ValidateAndSubmit(evt)
{
var isValid = true;
// Get Validator & Settings
var validator = $("#aspnetForm").validate();
var settings = validator.settings;
// Find the parent control that contains the elements to be validated
var $group = $(evt.currentTarget).parents('.validationGroup');
// Grab all the input elements (minus items listed below)
$group
.find(":input")
.not(":submit, :reset, :image, [disabled]")
.not(settings.ignore)
.each(function (i, item)
{
// Don't validate items without rules
if (!validator.objectLength($(item).rules()))
return true;
if (!$(item).valid())
isValid = false;
});
// If any control is the group fails, prevent default actions (aka: Submit)
if (!isValid) {
evt.preventDefault();
}
return isValid;
}
Related
I want to validate the p,li,div element texts. examples, I have an p tag with the class name "date". then the user can insert only a date.if they inserting text I want to display alert to the user in CKEDITOR.
Is it possible to in ckeditor without using any input fields<p class="date"></p>
<p class="date">31/07/2018</p>
<p class="date">a</p> I need to display error or alert.
how can i do without onchange events. is there have any default funtionality
You can get elements by class in jQuery. Then the validation process is straightforward
function isDate(value) {
var dateReg = /^\d{2}([./-])\d{2}\1\d{4}$/
return value.match(dateReg)
}
$("p.date").map(function() {
if(!isDate(this.innerHTML)) {
//alert("...");
}
});
As for the part - when to run these validation checks, you can call them on DOM updates like, insertion, deletion etc in the application layer.
I am using Sitecore 7.2 with Web Forms for Marketers 2.4.
Using wffm form designer I created a form that has a droplist in it.
I want to be able to hide or unhide another field in the same form based on the selected value of the droplist. Through my research I came up with exporting the form (via form designer export) and pointing the sublayout to that exported form.
I then added and onChange event to the droplist.
<cc3:droplist runat="server" title="Country" emptychoice="True" id="field_xyz" cssclass="scfDropListBorder fieldid.%7bxyz%7d name.Country" controlname="Country" fieldid="{xyz}" enableviewstate="False" onchange="checkField()">
I then added a javascript to the bottom of the page.
function checkField() {
alert("Hello! I am an alert box!!");
var a = document.getElementById("field_xyz");
alert(a.options[a.selectedIndex].value);
var cityTextBox = document.getElementById("field_abc").parentNode.parentNode;
if (a == "United States") {
cityTextBox.style.display = "block";
} else {
cityTextBox.style.display = "none";
}
alert("Ending Script");
}
I can get the 'Hello!' alert to show every time but not the 'ending' alert and the value of 'a' is always null from what I can tell.
Is what I'm trying to do even possible in Sitecore?
I read something else that said they had a problem because of encapsulation and protection levels.
I can also confirm that when I submit the form it does show up in the WFFM reports so I know it is submitting properly.
Any help/advice/direction would be appreciated.
I've never used the export functionality so can't comment to it's effectiveness or ease of use. My suggestion would be to simply use from custom css classes and jquery on the front-end to hide/show depending on the selected value.
Create 2 new css classes under /sitecore/system/Modules/Web Forms for Marketers/Settings/Meta data/Css Classes. Call them "hide-dependent" and "dependent-field"
Add your fields and then on the country field select "hide-dependent" as the CSS class, and for the City select "dependent-field"
Add the following Javascript to your own sites js file.
The code will bind a handler to fire onchange, checked the selected value and then hide/show all field with the dependent-field class. Specifying the chained field-border ensures that we are hiding the whole row and not just the select box.
(function ($) {
var HideDependentFied = function (value) {
var condition = (value == "USA");
$(".dependent-field.field-border").toggle(condition);
};
$(document).ready(function() {
var $field = $(".hide-dependent.field-border select");
$field.on("change", function() {
HideDependentFied(this.value)
});
HideDependentFied($field.val());
});
})($scw);
The above code is using an Immediately Invoked Function Expression and passing is $scw, which is the jQuery variable used by WFFM.
You may also want to fire the function on document ready, to ensure the field is hidden on load and only shown when the appropriate value is selected.
I have a form that is being validated with the jQuery validation plugin successfully.
Messages are displayed in the correct position and in the correct situations.
So far, so good.
I have 1 field that is being validated correctly, but I need to position that 1 validation message differently to the others. With 2 inputs next to each other, I want the validation to appear under them both (ie under the block that wraps them both) rather than to the right per individual inputs.
The validation on these 2 inputs are dependent on each other, ie at least one must have input. The validation rule works, it's just the positioning I'm struggling with.
I'm using the following validation syntax:
$('#formId').validate({
rules: {
},
messages : {
}
}
In my HTML I have created a label specifically for the (radio) field I am trying to customise:
<label for="radioName" id="radioNameId-invalid" class="error"">Some error message</label>
I tried adding content to the 'showErrors' function of validate, which works, but seemingly then doesn't show any of the other validation messages in my page.
showErrors: function(errors) {
var collectionMethodError = errors['collectionMethod'];
if(collectionMethodError) {
$('#radioNameId-invalid').text(errorString);
$('#radioNameId-invalid').css("display","block");
}
}
I want to enable this error AND then allow validator to continue to do its default behaviour for other fields.
If I remove the showErrors function, the other validation messages are displayed but not my custom one.
How can I get both behaviours?
I ended up using the errorPlacement function instead of the showErrors function:
errorPlacement: function(error, element){
$(error).insertAfter(element);
// special case for display
if($(element).attr("name")=="radioName") {
$(error).insertAfter("#anElement"));
$("label[for=radioName].error").attr("id","invalid-radio-message");
}
}
So in short I'm adding an ID to a label that validation plugin adds, then styling to that ID in my css.
That seems to do what I was trying to do. Now to workout the re-hiding of the message!
I'm trying to use jquery to check if every input-field has already been filled out. And if yes, I'd like to make a green border around the form.
This was my approach:
if($('input:text[value=""], textarea[value=""]').length == 0){
alert("DONE");
}
Hovever the value="" -Selector doesn't work.
It seems that the value-attribute only contains the input-field's default-value, but not the actual content inserted by the user - according to firebug.
This command alerts me the actual contents:
$('input:text[value!=""]').each(function(){
alert($(this).val());
});
My Question: Where are the actual input-field contents stored? And how can I use jQuery to check efficiently, if there are empty fields?
You are right, the attribute selectors only work with the value the attribute really has. Later on, changing the value of the input will only change the DOM element's internal state.
Where are the actual input-field contents stored?
You can access the value via the value property of the DOM element elementNode.value.
And how can I use jQuery to check efficiently, if there are empty fields?
You can use .filter:
$('input').filter(function() {
return !this.value;
});
A neat way of validating inputs is to attach a validation rule to the element for your script to find and validate against.
To make a field required:
<input type="text" data-validate="required" />
Your script:
$('[data-validate]').each(function() {
var rule = $(this).attr('data-validate'), value = $(this).val();
switch (rule) {
case 'required':
if (!value) {
alert('Field invalid!');
}
break;
}
});
It works pretty well for me.
You can make it more efficient by selecting only specific element types or children of a specific element (such as a form).
You could try using .filter() like this:
var empty = $('input:text').filter(function(){ return $(this).val() == "" }).length;
if(empty > 0){
alert("There are "+empty+" fields which have not been filled out");
}
my approach if you are not willing to use Jquery validate.
give a class to each of your input fields and then use Jquery class selector to test if those all have filled or not. You can use this even for dropdown too.
You should use this construction:
var incomplete = $('form :input').filter(function() {
return $(this).val() == '';
});
if (incomplete) {
alert('Please fill all fields!');
}
:input selector selects all input, textarea, select and button elements.
Read this: http://api.jquery.com/input-selector/
Here's the use case:
I have this long form with group of field that only becomes visible if the user makes a certain selection in one of the visible inputs. Reading Brad Wilson's post on the subject I thought jQuery.validator.unobtrusive.parse('.extra-data') where .extra-data is a class of a hidden div. No luck as the data was already there when the first parse was done.
So at the end I came up with this to remove the rules:
$('.data-panel').find('input[type="text"], textarea, select').each(function (i, item) {
var currentRules = $(item).rules('remove'); // Saving removed rules to a sorta dictionary
if (!$.isEmptyObject(currentRules)) {
removedRules[$(item).attr("name")] = currentRules;
}
});
and this to re-attach them:
$('.data-panel').find('input[type="text"], textarea, select').each(function (i, item) {
if (!$.isEmptyObject(removedRules[$(item).attr('name')])) {
$(item).rules('add', removedRules[$(item).attr('name')]);
}
});
Problem is, it feels kinda hacky as I'm literally going through each field removing and re-attaching those validation rules. My question is: isn't there a more straightforward way? Performance is also an issue, in one of those huge forms you can feel the delay between the click and the validation run.
Do not remove and re-attach rules. Just disable or enable inputs. Disabled fields do not participate in validation, neither do they get submitted to server.
//disable inputs. No validation will occur on these
$('.data-panel').find('input[type="text"], textarea, select').attr('disabled', 'disabled');
//enable inputs. Validation is re-enabled
$('.data-panel').find('input[type="text"], textarea, select').removeAttr('disabled');