Bootstrap select Plugin Not work With jQuery Validation - javascript

I design my HTML selectbox using bootstrap select plugin. Now, i add jQueryvalidation Plugin for validate my form But, Validation form not work with bootstrap select plugin.
DEMO HERE
HTML:
<form id="myform">
<select name="year" class="selectpicker">
<option value="">Year</option>
<option value="1">1955</option>
<option value="2">1956</option>
</select>
<br/>
<input type="submit" />
</form>
JS:
$(document).ready(function () {
$('select').selectpicker();
$('#myform').validate({ // initialize the plugin
rules: {
year: {
required: true,
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
NOTE: For check this conflict, remove Line 2 from JS, jQuery Validation Worked.
EDIT: adeneo Fix Problem Using ignore[] method : FIDDLE
$('#myform').validate({ // initialize the plugin
ignore: [],
rules: {
year: {
required: true
}
},
errorPlacement: function(error, element) {
if (element.attr("name") == "year") {
error.insertAfter(".bootstrap-select");
} else {
error.insertAfter(element);
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
Now This Worked but I have New Problem: In normal Validation after select fields, error message This field is required auto Hide( OR with add any css, show success message) but Now, error message is show after fix required field. in act: when we choose years, error message not hide.
How do fix This?

The select plugin hides the original select and creates a new one with an unordered list that updates the hidden selects value, but hidden elements are not validated by default by the validation plugin, you have to use the ignore rule and turn on validation for hidden elements
$('#myform').data("validator").settings.ignore = "";
FIDDLE
or
$('#myform').validate({ // initialize the plugin
ignore: [],
rules: {
year: {
required: true
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
FIDDLE
The Bootstrap select plugin creates a new dropdown from an unordered list, and the original select is hidden and it's value is updated when the user interacts with the unordered list.
This has the disadvantange of also moving the error message, as the original, now hidden select is the element being validated, and the new visible dropdown made up of an unordered list is inserted by Bootstrap below the original select in the DOM, the error message is inserted after the original select, but before the unordered list, so it appears above the custom dropdown, not below it like it would if the original select was used.
To fix it you can move the error message for any given element rather easily
$('#myform').validate({ // initialize the plugin
ignore: [],
rules: {
year: {
required: true
}
},
errorPlacement: function(error, element) {
if (element.attr("name") == "year") {
error.insertAfter(".bootstrap-select");
} else {
error.insertAfter(element);
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
FIDDLE

I had a similar issue so here's how I kind of extended #adeneo's answer together with lessons learnt from (the post here).
Note: For those who bump into this post, please read #adeneo's answer and
(the post here) to understand the scope of this solution.
The resulting code that very well functions flawlessly for me looks as follows:
jQuery / javascript:
$(document).ready(function() {
$.validator.setDefaults({
/*OBSERVATION (1): note the options used for "ignore"*/
ignore: ':not(select:hidden, input:visible, textarea:visible)',
/*...other options omitted to focus on the OP...*/
errorPlacement: function (error, element) {
/*OBSERVATION (2): note how selection is on the class "selectpicker"*/
if (element.hasClass('selectpicker')) {
error.insertAfter('.bootstrap-select');
} else {
error.insertAfter(element);
}
/*Add other (if...else...) conditions depending on your
* validation styling requirements*/
}
});
$('#myform').validate({
rules: {
'year': {
required: true
}
},
messages: {
'year': {
required: 'Please select a year from the dropdown'
}
}
});
});
HTML:
<form id="myform">
<select name="year" class="selectpicker">
<option value="">Year</option>
<option value="1">1955</option>
<option value="2">1956</option>
</select><br/>
<input type="submit" />
</form>
Explanation:
OBSERVATION (1): ignore: ':not(select:hidden, input:visible, textarea:visible)' simply means to ignore validation for all elements that's not a hidden <select>, that's not a visible <input> and that's not a visible <textarea>.
In simpler English, it just says to validate hidden <select>, ignore hidden <input> and ignore hidden <textarea> which is what we usually want in many cases. This I think is a better way to target what validation should be ignored or not.
Based on #Alvin Lee's answer here, setting the ignore options on the form element as follows was ok, but had its caveats;
$('#myform').validate().settings.ignore =
':not(select:hidden, input:visible, textarea:visible)';
The Problem: The bootstrap select element got validated but showed the default message This field is required on every other input element instead of overriding it with all the custom validation messages that were previously configured.
The fix: move the ignore setting into $.validator.setDefaults({...}) block... Voila! ! !
OBSERVATION (2):
Instead of doing if (element.attr("name") == "year") {...} like #adeneo pointed, I rather decided to select on class='selectpicker'... then in the javascript, check if the element had this class by doing if (element.hasClass('selectpicker')) {...}. This just ensures that this rule can be applied to all bootstrap-select elements as long as they're decorated with the class selectpicker.
Hope this is clear enough and helpful to somebody who has similar issues!

If you use 'selectpicker' class to initialize bootstrap-select widget, I recommend to partially solve the issue via changing default ignore settings for jquery validate:
$.validator.setDefaults({ ignore: ':hidden:not(.selectpicker)' });
before you validate your form. This is a bit better approach, and you also need to move error messages as adeneo supposed.
And still it will not have a similar validation behavior as select would have. The problem arise when the parent container is hidden. In case you do not use bootstrap-select your select will not validate when container is hidden, but when you use it still validates.

Related

ACF Select value adds class to div if value is not equal

I'm using ACF for the first time and struggling to get this to work. I've created a Select field with 2 options (This is controlled backend on the specific page)
<select id="acf-field_5bf80363f0c0f" class="" name="acf[field_5bf80363f0c0f]" data-ui="0" data-ajax="0" data-multiple="0" data-placeholder="Select" data-allow_null="0">
<option value="No Issues">No Issues</option>
<option value="Issues reported" selected="selected" data-i="0">Issues Reported</option>
</select>
What i would like to achive is that if selected option is not equal to No Issues, it would add a custom class (.Error) to the selected div with the id #ServiceStatus1 for example. I've attempted with my limited knowledge of jQuery but no joy.
Hope this makes sense, any advice is really appreciated.
<script type ="text/javascript">
$(function() {
$('#acf-field_5bf80363f0c0f').ready(function(){
$('.Error').hide();
$('#ServiceStatus1' + $('.Error').val() != 'No Issues').show();
});
});
</script>
Your question and your code seem to be asking different questions...
If you want to add/remove a class based on the value in the select, you could do:
$(function() {
function addServiceStatusClass(e){
if($(this).val() != 'No Issues'){
$('#ServiceStatus1').addClass('Error');
}else{
$('#ServiceStatus1').removeClass('Error');
}
}
$('#acf-field_5bf80363f0c0f').ready(addServiceStatusClass);
$('#acf-field_5bf80363f0c0f').change(addServiceStatusClass);
});
Example:
http://jsfiddle.net/m2o361th/2/
But if all you want to do is show/hide #ServiceStatus1 based on the value, you can do:
$(function() {
function addServiceStatusClass(e){
if($(this).val() != 'No Issues'){
$('#ServiceStatus1').show();
}else{
$('#ServiceStatus1').hide();
}
}
$('#acf-field_5bf80363f0c0f').ready(addServiceStatusClass);
$('#acf-field_5bf80363f0c0f').change(addServiceStatusClass);
});
Example:
http://jsfiddle.net/m2o361th/3/
Also as a reminder, if you're using the version of jQuery included with WordPress, you have to wrap your functions in a function mapped to jQuery:
(function($){
// contains one of the above functions...
})( jQuery );
Thank you so much for the above. I've tweaked your above code to factor in that the select field is backend and my div is frontend. The working code for this is...
$(function() {
function addServiceStatusClass(e){
if($('#Multistream').text() != 'No Issues'){
$('#ServiceStatus1').addClass('Error');
}else{
$('#ServiceStatus1').removeClass('Error');
}
}
$('#acf-field_5bf80363f0c0f').ready(addServiceStatusClass);
$('#acf-field_5bf80363f0c0f').change(addServiceStatusClass);
});
})( jQuery );

how to prevent dynamic span formation in JavaScript validation

I have a registration form, validation is done by JavaScript. If validation fails it will shows error in span attribute in dynamically bellow eachy field. But problem is that if the validation is true, the span is generated but not visible. So there is additional blank space after onchange. How can I solve this?
form.validate({
doNotHideMessage: false, //this option enables to show the error/success messages on tab switch.
errorElement: 'span', //default input error message container
errorClass: 'validate-inline', // default input error message class
focusInvalid: false, // do not focus the last invalid input
rules: {
birth_town: {
parentname: true,
required: true
},
birth_district: {
parentname: true,
required: true
},
},
messages: {
name: {
required: "select one ",
minlength: jQuery.format("select one")
}
},
});
Try display:none instead of visibility:hidden.
JSFiddle
Code
function hide() {
var err = document.getElementById("err1");
err.className = "hidden";
}
function invisible() {
var err = document.getElementById("err1");
err.className = "invisible";
}
(function() {
var val = document.getElementById("txt1").textContent;
if (val.length == 0) {
var err = document.getElementById("err1");
err.innerHTML = "Enter some text";
err.className = "invisible";
}
})()
.hidden {
visibility: hidden;
}
.invisible {
display: none
}
<input type="text" id="txt1">
<br/> <span class="error" id="err1"></span>
<input type="text" id="txt2">
<br/> <span class="error" id="err2"></span>
<button onclick="hide()">hidden</button>
<button onclick="invisible()">invisible</button>
I think that your problem is in CSS.
You probably set somewhere top or bottom (or both) margins for your validate-inline class. The Validate plugin attaches this class to both incorrectly filled input and following error span.
You can see it in this JS Fiddle.
Try to click 'Submit' with inputs empty. You will see error messages popping up. Then try to fill the first input. Error for that one hides but space remains. This is because the second input keeps class validate-inline and it is its margin that keeps the space not the hidden error span of the first input.
Try to remove margins from validate-inline class in your CSS and see if that helps.
PS. Also I'm not sure about parentname: true - didn't find this in plugin rules documentation and jsFiddle won't work with it so I removed them from rules.

How can perform a validation JQuery script after that a div containing the input field of a form is loaded?

I am absolutly new in JQuery and I have the following doubt.
I know that doing:
$(document).ready(function() {
DO SOMETHING
..............................
..............................
..............................
}
the behavior implemented by the function() body is performed after that the document is completly show.
But for example I have the following situation. Into a page that use Struts 2 tag library (but this is not important I have a form:
<s:form id="projectForm" >
<sj:div id="resultEvents" href="%{loadFolderTechId}"
formIds="treeForm"
class="result ui-widget-content ui-corner-all"
loadingText=" "
onBeforeTopics="before"
onCompleteTopics="complete"
deferredLoading="true"
reloadTopics="reloadEvents"
>
</sj:div>
<s:submit style="display:none" id="submitButton" action="projectCreationAction"/>
</s:form>
The s:form tag is a Struts 2 tag that simply wrap a standard HTML form.
The sj:div tag is a Struts 2 tag that wrap a div containing the input field of the form. This is definied into another JSP page and this is showed only after a specific event (when the user click on a button). It simply generate a standard HTML div with id=resultEvents containing the form input fields.
So now I want to use the JQuery validator for the input field values but I can't load it when the document is ready by the $(document).ready() because when the document is ready the input field of my form is not loaded in the DOM.
I have to do something like this:
$(document).ready(function(){
alert("VALIDATION")
var validator = $("#projectForm").validate({
rules: {
"kmProjectInfo.name": "required"
},
messages: {
"kmProjectInfo.name": "Please enter a project name"
}
});
But insted the ready function I have to load this script after that the content of the div having id=resultEvents is loaded.
How can I do it? Is it possible in someway?
Tnx
Ideas:
1) If your form is loaded by another module (or when the $(document).ready is called), you'll have to set a callback or dispatch an event that says when the form is ready.
function validator() {
var validator = $("#projectForm").validate({
rules: {
"kmProjectInfo.name": "required"
},
messages: {
"kmProjectInfo.name": "Please enter a project name"
}
});
...
}
// form_module can be a module you use to load
// or a struts2 js api or some jquery function that does the work.
$(document).ready(function() {
form_module.load("url/to/form?", {
"on_form_loaded": function() { validator(); }
})
});
2) Define the validator when you click submit or tries to submit the form, but this way you can't validate when the form is loaded.
function validator() {
var validator = $("#projectForm").validate({
rules: {
"kmProjectInfo.name": "required"
},
messages: {
"kmProjectInfo.name": "Please enter a project name"
}
});
...
}
// ?
$("#submitButton").click(function() { validator(); });
// ?
$("#projectForm").submit(function() { validator(); });

Add jquery validation

I'm trying to build a server control that has a radiobuttonlist with 2 items and a textbox.
THe radio buttons are YES en NO options.
When YES is selected I want the textbox to be visible and it must be required to fill in.
On NO, the textbox becomes invisible.
I manages to get the textbox to appear and disappear based on the option choice.
But how do I add validation to the textbox and remove it when not visible?
I have tried it with the ASP validators, but the jquery doesn't disable them when the textbox is not visible.
I tried something like this, but it is not working:
<script type="text/javascript">
$(function()
{
$('#TravelOption2_rbList').change(function()
{
var index = $('#TravelOption2_rbList input[type=radio]:checked').val();
if (index != '0')
{
$('#TravelOption2_lblName2').css({'visibility':'visible'});
$('#TravelOption2_txtName1').css({'visibility':'visible'});
$('#TravelOption2_lblName3').css({'visibility':'visible'});
// create validator (not working)
$('#TravelOption2_txtName1').rules('add', {
required: true,
minlength: 2,
messages: { required: 'Required input', minlength: 'Please enter the cost.' }
});
} else {
$('#TravelOption2_lblName2').css({'visibility':'hidden'});
$('#TravelOption2_txtName1').css({'visibility':'hidden'});
$('#TravelOption2_lblName3').css({'visibility':'hidden'});
// remove the validator here
}
});
});
</script>
I have seen a lot of examples but they are not working for me.
Would it not be easier to simply check if the textbox has at least 2 characters in it when you submit it's contents? I'm assuming this is some sort of input form.
<script type="text/javascript">
$(function() {
$('#submitButton').on('click', function(){
if ($('#TravelOption2_txtName1').val().length > 1 ) {
//Textbox has at least 2 characters in it
}
})
});
</script>
This article helped me solve this problem.
Enable-Disable-ASPNet-Validator-Client-Side-Validation-using-JavaScript-or-jQuery

onClick remote validation for dropdown field

I am using JQuery remote validation on drop-down field to check whether the selected field already exists or not. The overall code is working fine and validates properly. But the issue is remote validation sending an ajax call after onChange event, means it is showing unique key validation error after clicking anywhere on page.
I want to validate it once user clicks on dropdown option. I tried onclick:true but it's not working. Please check my code:
$("#myform").validate({
// onclick:true,
// onkeyup:true,
rules: {
"customer[customer_personal_details_id]": {
required: true,
remote: {
url: "/validation/check",
type: "post",
data: {
columnVal: function () {
return $("#customer_customer_personal_details_id").val();
}
}
}
}
},
messages: {
"customer[customer_personal_details_id]": {
required: "Please Select Account Holder",
remote: "One active account already exists. Duplicate accounts are not allowed."}
}
});
Thanks. Any help would be appreciated.
Try this - assuming you have <SELECT ID="DROPDOWN_ID">
$('#DROPDOWN_ID').on('click', function() {
$("#myform").validate();
});
The select's change event is a much better indicator of when to validate but there's no onchange option. The following should work:
$(function() {
$('select').on('change', function() {
$(this).trigger('focusout');
})
.on('focusout',function(e) {
e.preventDefault();
});
});
Triggering focusout should trigger a validate to be fired on the select element unless the onfocusout option is set to false. You may want to prevent the default behavior of focusout so that it does not trigger a remote validation twice.
In the demo below you'll see that as soon as you select a new value in select element, an attempt to make an ajax call is made -- see network tab of dev tools -- and on focusout no request attempt is made.
JSFIDDLE DEMO
onfocusout Type: Boolean or Function() Validate elements (except
checkboxes/radio buttons) on blur. If nothing is entered, all rules
are skipped, except when the field was already marked as invalid.
http://jqueryvalidation.org/category/plugin/
I do not use: "JQuery Remote Validation", but this code might help you:
JavaScript code:
window . onload = function ()
{
"use strict";
document . querySelector ( "form#myform > select" ) . selectedIndex = -1;
}
function test ()
{
"use strict";
if ( typeof customOption === "undefined" ) { alert ( "FATAL SYSTEM ERROR !" ); return; }
alert ( "Valid option selected ! Congratulations !\nYour selected value is: \"" + customOption + "\"" );
}
and the HTML5 code:
<select onchange="customOption = this . options [ this . selectedIndex ] . value;">
<!-- ( ... ) -->
</select>
This is only demonstration. You can call your function, so you can: "validate it once user clicks on dropdown option" by change HTML5 code ( select element onchange attribute ).
Working fiddle: JSFiddle

Categories