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
Related
I'm trying to add a quick conditional logic to my Laravel project. If a "create_copay" text input is anything other than 0.00, my "create_ams_fee" field should display 0.00. Else, it will be 7.00. However, my code displays no change whatsoever in the create_ams_fee field.
Form Fields (Laravel Collective)
<div class="form-group">
{{Form::label('copay', 'Copay')}}
{{Form::text('copay', '', ['class' => $errors->has('copay') ? 'form-control border border-danger' : 'form-control', 'id' => 'create_copay'])}}
</div><!-- /form-group -->
<div class="form-group">
{{Form::label('ams_fee', 'AMS Fee')}}
{{Form::text('ams_fee', '', ['class' => 'form-control', 'id' => 'create_ams_fee'])}}
</div><!-- /form-group -->
Script
// Calculate AMS Fee field
$('#create_copay').change(function() {
if ($('#create_copay').val() == '0.00') {
$('#create_ams_fee').val('7.00');
} else {
$('#create_ams_fee').val('0.00');
};
});
Edit
This seems to be turning into a dynamic loading issue. The codeblock below is what I'm resulting to try and test. The parent container of these inputs has an id of create_financials. I currently am having no success finding a way to trigger an event by changing the create_copay field.
$( document ).ready( function() {
$('#create_financials').on('input', '#create_copay', function() {
console.log('SUCCESS');
});
});
You are using the 'change' event - this is only fired when focus is taken out of the element (it is blurred) and it has changed, or the form is submitted, or certain other times.
You could use the keydown or keyup events, but a better one is the 'input' event.
If this is a number input, you should use the input type 'number' rather than text - however, if you don't want to or can't do that, casting the text from the input to a number might also be beneficial:
$('#create_copay').on('input', function() {
if ($('#create_copay').val()/1 == 0) {
$('#create_ams_fee').val('7.00');
} else {
$('#create_ams_fee').val('0.00');
};
});
Please see this codepen for a working example:
https://codepen.io/manticorp/pen/wYpXWY
Using the html inspector (right click, inspect element) are you sure your inputs have the ids specified? (create_copay and create_ams_fee).
Also, I've just seen your inputs may already be populated, in which case something like this would be better:
$(function() { // jQuery domready event
$('#create_copay').on('input', updateFields);
function updateFields() {
if ($('#create_copay').val()/1 == 0) {
$('#create_ams_fee').val('7.00');
} else {
$('#create_ams_fee').val('0.00');
};
}
updateFields();
});
If you are creating these fields dynamically, or inserting them into the document after load somehow, then you will need to attach the event to the document/a container element:
$(function() { // jQuery domready event
$('#theContainer').on('input', '#create_copay', updateFields);
function updateFields() {
if ($('#create_copay').val()/1 == 0) {
$('#create_ams_fee').val('7.00');
} else {
$('#create_ams_fee').val('0.00');
};
}
updateFields();
});
Use the keydown event for input field. Change takes effect after the input element loses focus.
i have this column with dropdown, currently when i select any value from the dropdown it it gets saved, i would like to add a validation while selecting a value from dropdown before saving, for example,
{name:'color_name',
cellattr: function (rowid, cellValue) {
if ($.inArray(cellValue, hilightcolorcell) < 0) {
return " class='redcells'";
}
},editable:true,edittype:"select",editoptions:
{value:"PURPLE:PURPLE;PINK:PINK;GREEN:GREEN"}}
if the selected value was PINK, i wanted to have a validation prompt with Save and Cancel button something like this, Selected Value is : PINK, SAVE CANCEL
this is demo link https://jsfiddle.net/kwu7v3fc/3/
please help.
There are many ways to implement your requirement. The most native would seems to me to ask the confirmation from the user directly on change of the select option and before real saving it. One can add "change" event handler, which do all you need. The corresponding implementation will look like on the example below
editoptions: {
value: "PURPLE:PURPLE;PINK:PINK;GREEN:GREEN",
dataEvents: [
{
type: "change",
fn: function (e) {
if ($(this).val() === "PINK") {
if (!confirm("Are you sure you want PINK?")) {
// reset the value to the previous one
var savedRow = $("#rowed5").jqGrid("getGridParam", "savedRow");
$(this).val(savedRow[0].v);
}
}
}
}
]
}
See the modified demo https://jsfiddle.net/OlegKi/kwu7v3fc/5/
I am trying to disable the submit button if the username textbox field is empty.
$("#txtUserName").bind("input propertychange change keyup paste", setButtonState);
var setButtonState = function () {
if ($("#txtUserName").val().trim() == "") {
$("#login").attr("disabled", true);
}
else {
$("#login").removeAttr("disabled");
}
}
The above code is working fine in all scenarios except that,when the user selects username which is saved earlier(autocomplete).
I cannot set the autocomplete off option for the textbox.
How can I catch the event when user selects text in autocomplete usernames?
Just bind your input field to the additional event select, which is fired when a user selects something from his autocompletion.
This would be your code then. I just added select and rearranged your code a little bit. Also I run setButtonState() once at the domready to be sure it's disabled.
var setButtonState = function () {
if ($("#txtUserName").val().trim() == "") {
$("#login").attr("disabled", true);
}
else {
$("#login").removeAttr("disabled");
}
}
$("#txtUserName").bind("input propertychange change keyup paste select", setButtonState);
setButtonState();
I have also updated the jsfiddle to demonstrate it.
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.
I have the below script:
$("#product1").autocomplete({
source: "get_sku_family",
messages: {
noResults: '',
results: function () {}
},
select: function (event, ui) {
var selectedObj = ui.item;
$.post('get_as_09',
{
data: selectedObj.value
},
function (result) {
if (result[0] > 0) {
$('#h09_1').attr('checked', 'checked');
} else {
$('#h09_1').removeAttr('checked');
}
}
});
}
});
This has an autocomplete field that when text is entered provides options from a database. this works. then on clicking an option from the autocomplete, it queries the database with a function(get_as_09) and checks the checkbox based on the result.
Again this works 100%.
What I do want to change though, is that when I enter a new value on the autocomplete, it must clear the checkboxes before applying the new database lookup logic to check the boxes.
I just don't know where to add the $('#h09_1').removeAttr('checked');
Thanks and Regards...
any help appreciated
UPDATE Ripu
if(data:selectedObj.value.length ==0 ){$('#h09_1').removeAttr('checked');};
$.post('get_as_09', {data:selectedObj.value},function(result) {
if(result[0] > 0) {
$('#h09_1').attr('checked','checked');
} else {
$('#h09_1').removeAttr('checked');
}
});
before this line
$.post('get_as_09', {data:selectedObj.value},function(result) {
check if the value of data:selectedObj.value is empty. If it is empty, then you don't need to make a post request, just simply uncheck the checkbox
try to make it on texbox on change event means when you enter the new value in auto complete make it there to clear any thing you want check
Why dont you clear your checkboxes on focus of the auto-complete field.
Here is the documentation about this event http://api.jqueryui.com/autocomplete/#event-focus
as you said just a $('#h09_1').removeAttr('checked'); should suffice.
focus: function( event, ui ) {
$('#h09_1').removeAttr('checked');
}
what if you put before
$.post('get_as_09', {data:selectedObj.value},function(result) {
so everytime before you put smth inside your $('#h09_1') you clean it?
What if you attach an event listener on the element based on the keypress event? Something like this:
$(selectedObj).one('keypress', function (e) {
var checkbox = $('#h09_1');
if (selectObj.val().length > 0) {
checkbox.attr('checked', false);
}
});
This way you know somebody is typing in the field before you clear it. You could bind the event listener after each database lookup. Just an idea.