Validate dependent select options with jQuery Validation plugin The Next CEO of Stack OverflowIs there an “exists” function for jQuery?How to validate an email address in JavaScript?How do I check if an element is hidden in jQuery?Setting “checked” for a checkbox with jQuery?How can I know which radio button is selected via jQuery?How to check whether a checkbox is checked in jQuery?How can I select an element with multiple classes in jQuery?Get selected text from a drop-down list (select box) using jQueryjQuery scroll to element“Thinking in AngularJS” if I have a jQuery background?

How to compactly explain secondary and tertiary characters without resorting to stereotypes?

Which acid/base does a strong base/acid react when added to a buffer solution?

Is it a bad idea to plug the other end of ESD strap to wall ground?

How to show a landlord what we have in savings?

Can this transistor (2N2222) take 6 V on emitter-base? Am I reading the datasheet incorrectly?

What happens if you break a law in another country outside of that country?

Does Germany produce more waste than the US?

Man transported from Alternate World into ours by a Neutrino Detector

Avoiding the "not like other girls" trope?

Early programmable calculators with RS-232

Incomplete cube

Is it okay to majorly distort historical facts while writing a fiction story?

My boss doesn't want me to have a side project

Does the Idaho Potato Commission associate potato skins with healthy eating?

Free fall ellipse or parabola?

How to implement Comparable so it is consistent with identity-equality

How do I secure a TV wall mount?

How should I connect my cat5 cable to connectors having an orange-green line?

Is it correct to say moon starry nights?

What is the difference between 'contrib' and 'non-free' packages repositories?

Compensation for working overtime on Saturdays

That's an odd coin - I wonder why

How can a day be of 24 hours?

Is a distribution that is normal, but highly skewed, considered Gaussian?



Validate dependent select options with jQuery Validation plugin



The Next CEO of Stack OverflowIs there an “exists” function for jQuery?How to validate an email address in JavaScript?How do I check if an element is hidden in jQuery?Setting “checked” for a checkbox with jQuery?How can I know which radio button is selected via jQuery?How to check whether a checkbox is checked in jQuery?How can I select an element with multiple classes in jQuery?Get selected text from a drop-down list (select box) using jQueryjQuery scroll to element“Thinking in AngularJS” if I have a jQuery background?










0















INTRODUCTION



I am using jQuery Validation plugin to validate form before submitting it to the server. For simple cases it works great. Yet i find official documentation lacking some more advanced examples.



IMAGINE



Imagine there is internet shop with 3 locations (Berlin, Paris and Rome). Yet delivery with courier service is available only in one location (Berlin). Note that: orders can be sent by post to all three locations.



I would like to make sure that validation displays an error if user chooses courier service in conjunction with Rome or Paris.



PROBLEM



I am trying to validate two selects that depend on each others option values.
Though, i can not figure out how to make it happen.



CODE



JsFiddle of my code



html



<form id="myForm" name="myForm">
<p><b>Order delivery</b></p>
<p>
City<br />
<select name="city" id="city">
<option selected value="">-- Please choose destination --</option>
<option value="1">Berlin</option>
<option value="2">Paris</option>
<option value="3">Rome</option>
</select>
</p>
<p>
Delivery method<br />
<select name="delivery" id="delivery">
<option selected value="">-- Please choose delivery method --</option>
<option value="1">By post</option>
<option value="2">By courier</option>
</select>
</p>
<input type="submit" />
</form>


javascript



$( document ).ready( function () 
jQuery.validator.addMethod("valueIsDeliveryPost", function(elementValue, element, param)
if (elementValue == 1)
return true;
else
return false;

, "Value must equal param.");

jQuery.validator.addMethod("valueIsDeliveryCourier", function(elementValue, element, param)
if (elementValue == 2)
return true;
else
return false;

, "Value must equal param.");

jQuery.validator.addMethod("valueIsEqualTo", function(elementValue, element, param)
return elementValue == param;
, "Value must equal param.");

jQuery.validator.addMethod("valueIsNotEqualTo", function(elementValue, element, param)
return elementValue != param;
, "Value must not equal param.");

$("#myForm").validate(
debug: true,
rules:
city:
required: true,
valueIsNotEqualTo: "default"
,
delivery:
required: true,
valueIsNotEqualTo: "default",
valueIsDeliveryPost:
param: 1, // if delivery by post is selected
depends: function(element)
var cityVal = $("#city").val();
if ((cityVal != "") && (cityVal == 1)) // if Berlin
return false;
else if ((cityVal != "") && (cityVal == 2)) // if Paris
return false;
else if ((cityVal != "") && (cityVal == 3)) // if Rome
return false;
/* else
return true;
*/

,
valueIsDeliveryCourier:
param: 2, // if delivery by courier is selected
depends: function(element)
var cityVal = $("#city").val();
if ((cityVal != "") && (cityVal == 1)) // if Berlin
return true;
else if ((cityVal != "") && (cityVal == 2)) // if Paris
return false;
else if ((cityVal != "") && (cityVal == 3)) // if Rome
return false;
/* else
return true;
*/


,
,
messages:
city:
required: "Please select your city!",
valueIsNotEqualTo: "Please select your city!"
,
delivery:
required: "Please select delivery method!",
valueIsNotEqualTo: "Please select delivery method!",
valueIsDeliveryPost: "Delivery by post is possible for all cities!",
valueIsDeliveryCourier: "Courier delivery is possible only in Berlin!"
,
errorElement: "em",
errorPlacement: function (error, element)
return false;
,
invalidHandler: function(form, validator)
var errors = validator.numberOfInvalids();
if (errors)
// Only show first invalid rule message
alert(validator.errorList[0].message);
// Set focus
validator.errorList[0].element.focus();

,
highlight: function (element, errorClass, validClass)
$(element).addClass("is-invalid").removeClass( "is-valid" );
,
unhighlight: function (element, errorClass, validClass)
$(element).addClass("is-valid").removeClass( "is-invalid" );
,
submitHandler: function(form)
alert('valid form');


);
);


FINALLY



I think that cause of the problem might be wrong logic in dependent select validation code.



What am i doing wong?



Please share your expertize and ideas.










share|improve this question



















  • 1





    I’ve never seen this validation plugin before, but looking at the official documentation looks like you should put the simple validation logic (Courier only in Berlin) directly in a addMethod function

    – Davide Vitali
    Mar 21 at 20:24















0















INTRODUCTION



I am using jQuery Validation plugin to validate form before submitting it to the server. For simple cases it works great. Yet i find official documentation lacking some more advanced examples.



IMAGINE



Imagine there is internet shop with 3 locations (Berlin, Paris and Rome). Yet delivery with courier service is available only in one location (Berlin). Note that: orders can be sent by post to all three locations.



I would like to make sure that validation displays an error if user chooses courier service in conjunction with Rome or Paris.



PROBLEM



I am trying to validate two selects that depend on each others option values.
Though, i can not figure out how to make it happen.



CODE



JsFiddle of my code



html



<form id="myForm" name="myForm">
<p><b>Order delivery</b></p>
<p>
City<br />
<select name="city" id="city">
<option selected value="">-- Please choose destination --</option>
<option value="1">Berlin</option>
<option value="2">Paris</option>
<option value="3">Rome</option>
</select>
</p>
<p>
Delivery method<br />
<select name="delivery" id="delivery">
<option selected value="">-- Please choose delivery method --</option>
<option value="1">By post</option>
<option value="2">By courier</option>
</select>
</p>
<input type="submit" />
</form>


javascript



$( document ).ready( function () 
jQuery.validator.addMethod("valueIsDeliveryPost", function(elementValue, element, param)
if (elementValue == 1)
return true;
else
return false;

, "Value must equal param.");

jQuery.validator.addMethod("valueIsDeliveryCourier", function(elementValue, element, param)
if (elementValue == 2)
return true;
else
return false;

, "Value must equal param.");

jQuery.validator.addMethod("valueIsEqualTo", function(elementValue, element, param)
return elementValue == param;
, "Value must equal param.");

jQuery.validator.addMethod("valueIsNotEqualTo", function(elementValue, element, param)
return elementValue != param;
, "Value must not equal param.");

$("#myForm").validate(
debug: true,
rules:
city:
required: true,
valueIsNotEqualTo: "default"
,
delivery:
required: true,
valueIsNotEqualTo: "default",
valueIsDeliveryPost:
param: 1, // if delivery by post is selected
depends: function(element)
var cityVal = $("#city").val();
if ((cityVal != "") && (cityVal == 1)) // if Berlin
return false;
else if ((cityVal != "") && (cityVal == 2)) // if Paris
return false;
else if ((cityVal != "") && (cityVal == 3)) // if Rome
return false;
/* else
return true;
*/

,
valueIsDeliveryCourier:
param: 2, // if delivery by courier is selected
depends: function(element)
var cityVal = $("#city").val();
if ((cityVal != "") && (cityVal == 1)) // if Berlin
return true;
else if ((cityVal != "") && (cityVal == 2)) // if Paris
return false;
else if ((cityVal != "") && (cityVal == 3)) // if Rome
return false;
/* else
return true;
*/


,
,
messages:
city:
required: "Please select your city!",
valueIsNotEqualTo: "Please select your city!"
,
delivery:
required: "Please select delivery method!",
valueIsNotEqualTo: "Please select delivery method!",
valueIsDeliveryPost: "Delivery by post is possible for all cities!",
valueIsDeliveryCourier: "Courier delivery is possible only in Berlin!"
,
errorElement: "em",
errorPlacement: function (error, element)
return false;
,
invalidHandler: function(form, validator)
var errors = validator.numberOfInvalids();
if (errors)
// Only show first invalid rule message
alert(validator.errorList[0].message);
// Set focus
validator.errorList[0].element.focus();

,
highlight: function (element, errorClass, validClass)
$(element).addClass("is-invalid").removeClass( "is-valid" );
,
unhighlight: function (element, errorClass, validClass)
$(element).addClass("is-valid").removeClass( "is-invalid" );
,
submitHandler: function(form)
alert('valid form');


);
);


FINALLY



I think that cause of the problem might be wrong logic in dependent select validation code.



What am i doing wong?



Please share your expertize and ideas.










share|improve this question



















  • 1





    I’ve never seen this validation plugin before, but looking at the official documentation looks like you should put the simple validation logic (Courier only in Berlin) directly in a addMethod function

    – Davide Vitali
    Mar 21 at 20:24













0












0








0








INTRODUCTION



I am using jQuery Validation plugin to validate form before submitting it to the server. For simple cases it works great. Yet i find official documentation lacking some more advanced examples.



IMAGINE



Imagine there is internet shop with 3 locations (Berlin, Paris and Rome). Yet delivery with courier service is available only in one location (Berlin). Note that: orders can be sent by post to all three locations.



I would like to make sure that validation displays an error if user chooses courier service in conjunction with Rome or Paris.



PROBLEM



I am trying to validate two selects that depend on each others option values.
Though, i can not figure out how to make it happen.



CODE



JsFiddle of my code



html



<form id="myForm" name="myForm">
<p><b>Order delivery</b></p>
<p>
City<br />
<select name="city" id="city">
<option selected value="">-- Please choose destination --</option>
<option value="1">Berlin</option>
<option value="2">Paris</option>
<option value="3">Rome</option>
</select>
</p>
<p>
Delivery method<br />
<select name="delivery" id="delivery">
<option selected value="">-- Please choose delivery method --</option>
<option value="1">By post</option>
<option value="2">By courier</option>
</select>
</p>
<input type="submit" />
</form>


javascript



$( document ).ready( function () 
jQuery.validator.addMethod("valueIsDeliveryPost", function(elementValue, element, param)
if (elementValue == 1)
return true;
else
return false;

, "Value must equal param.");

jQuery.validator.addMethod("valueIsDeliveryCourier", function(elementValue, element, param)
if (elementValue == 2)
return true;
else
return false;

, "Value must equal param.");

jQuery.validator.addMethod("valueIsEqualTo", function(elementValue, element, param)
return elementValue == param;
, "Value must equal param.");

jQuery.validator.addMethod("valueIsNotEqualTo", function(elementValue, element, param)
return elementValue != param;
, "Value must not equal param.");

$("#myForm").validate(
debug: true,
rules:
city:
required: true,
valueIsNotEqualTo: "default"
,
delivery:
required: true,
valueIsNotEqualTo: "default",
valueIsDeliveryPost:
param: 1, // if delivery by post is selected
depends: function(element)
var cityVal = $("#city").val();
if ((cityVal != "") && (cityVal == 1)) // if Berlin
return false;
else if ((cityVal != "") && (cityVal == 2)) // if Paris
return false;
else if ((cityVal != "") && (cityVal == 3)) // if Rome
return false;
/* else
return true;
*/

,
valueIsDeliveryCourier:
param: 2, // if delivery by courier is selected
depends: function(element)
var cityVal = $("#city").val();
if ((cityVal != "") && (cityVal == 1)) // if Berlin
return true;
else if ((cityVal != "") && (cityVal == 2)) // if Paris
return false;
else if ((cityVal != "") && (cityVal == 3)) // if Rome
return false;
/* else
return true;
*/


,
,
messages:
city:
required: "Please select your city!",
valueIsNotEqualTo: "Please select your city!"
,
delivery:
required: "Please select delivery method!",
valueIsNotEqualTo: "Please select delivery method!",
valueIsDeliveryPost: "Delivery by post is possible for all cities!",
valueIsDeliveryCourier: "Courier delivery is possible only in Berlin!"
,
errorElement: "em",
errorPlacement: function (error, element)
return false;
,
invalidHandler: function(form, validator)
var errors = validator.numberOfInvalids();
if (errors)
// Only show first invalid rule message
alert(validator.errorList[0].message);
// Set focus
validator.errorList[0].element.focus();

,
highlight: function (element, errorClass, validClass)
$(element).addClass("is-invalid").removeClass( "is-valid" );
,
unhighlight: function (element, errorClass, validClass)
$(element).addClass("is-valid").removeClass( "is-invalid" );
,
submitHandler: function(form)
alert('valid form');


);
);


FINALLY



I think that cause of the problem might be wrong logic in dependent select validation code.



What am i doing wong?



Please share your expertize and ideas.










share|improve this question
















INTRODUCTION



I am using jQuery Validation plugin to validate form before submitting it to the server. For simple cases it works great. Yet i find official documentation lacking some more advanced examples.



IMAGINE



Imagine there is internet shop with 3 locations (Berlin, Paris and Rome). Yet delivery with courier service is available only in one location (Berlin). Note that: orders can be sent by post to all three locations.



I would like to make sure that validation displays an error if user chooses courier service in conjunction with Rome or Paris.



PROBLEM



I am trying to validate two selects that depend on each others option values.
Though, i can not figure out how to make it happen.



CODE



JsFiddle of my code



html



<form id="myForm" name="myForm">
<p><b>Order delivery</b></p>
<p>
City<br />
<select name="city" id="city">
<option selected value="">-- Please choose destination --</option>
<option value="1">Berlin</option>
<option value="2">Paris</option>
<option value="3">Rome</option>
</select>
</p>
<p>
Delivery method<br />
<select name="delivery" id="delivery">
<option selected value="">-- Please choose delivery method --</option>
<option value="1">By post</option>
<option value="2">By courier</option>
</select>
</p>
<input type="submit" />
</form>


javascript



$( document ).ready( function () 
jQuery.validator.addMethod("valueIsDeliveryPost", function(elementValue, element, param)
if (elementValue == 1)
return true;
else
return false;

, "Value must equal param.");

jQuery.validator.addMethod("valueIsDeliveryCourier", function(elementValue, element, param)
if (elementValue == 2)
return true;
else
return false;

, "Value must equal param.");

jQuery.validator.addMethod("valueIsEqualTo", function(elementValue, element, param)
return elementValue == param;
, "Value must equal param.");

jQuery.validator.addMethod("valueIsNotEqualTo", function(elementValue, element, param)
return elementValue != param;
, "Value must not equal param.");

$("#myForm").validate(
debug: true,
rules:
city:
required: true,
valueIsNotEqualTo: "default"
,
delivery:
required: true,
valueIsNotEqualTo: "default",
valueIsDeliveryPost:
param: 1, // if delivery by post is selected
depends: function(element)
var cityVal = $("#city").val();
if ((cityVal != "") && (cityVal == 1)) // if Berlin
return false;
else if ((cityVal != "") && (cityVal == 2)) // if Paris
return false;
else if ((cityVal != "") && (cityVal == 3)) // if Rome
return false;
/* else
return true;
*/

,
valueIsDeliveryCourier:
param: 2, // if delivery by courier is selected
depends: function(element)
var cityVal = $("#city").val();
if ((cityVal != "") && (cityVal == 1)) // if Berlin
return true;
else if ((cityVal != "") && (cityVal == 2)) // if Paris
return false;
else if ((cityVal != "") && (cityVal == 3)) // if Rome
return false;
/* else
return true;
*/


,
,
messages:
city:
required: "Please select your city!",
valueIsNotEqualTo: "Please select your city!"
,
delivery:
required: "Please select delivery method!",
valueIsNotEqualTo: "Please select delivery method!",
valueIsDeliveryPost: "Delivery by post is possible for all cities!",
valueIsDeliveryCourier: "Courier delivery is possible only in Berlin!"
,
errorElement: "em",
errorPlacement: function (error, element)
return false;
,
invalidHandler: function(form, validator)
var errors = validator.numberOfInvalids();
if (errors)
// Only show first invalid rule message
alert(validator.errorList[0].message);
// Set focus
validator.errorList[0].element.focus();

,
highlight: function (element, errorClass, validClass)
$(element).addClass("is-invalid").removeClass( "is-valid" );
,
unhighlight: function (element, errorClass, validClass)
$(element).addClass("is-valid").removeClass( "is-invalid" );
,
submitHandler: function(form)
alert('valid form');


);
);


FINALLY



I think that cause of the problem might be wrong logic in dependent select validation code.



What am i doing wong?



Please share your expertize and ideas.







javascript jquery html5 jquery-validate






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 21 at 21:36









Sparky

82.9k20152242




82.9k20152242










asked Mar 21 at 20:00









RikijsRikijs

2221225




2221225







  • 1





    I’ve never seen this validation plugin before, but looking at the official documentation looks like you should put the simple validation logic (Courier only in Berlin) directly in a addMethod function

    – Davide Vitali
    Mar 21 at 20:24












  • 1





    I’ve never seen this validation plugin before, but looking at the official documentation looks like you should put the simple validation logic (Courier only in Berlin) directly in a addMethod function

    – Davide Vitali
    Mar 21 at 20:24







1




1





I’ve never seen this validation plugin before, but looking at the official documentation looks like you should put the simple validation logic (Courier only in Berlin) directly in a addMethod function

– Davide Vitali
Mar 21 at 20:24





I’ve never seen this validation plugin before, but looking at the official documentation looks like you should put the simple validation logic (Courier only in Berlin) directly in a addMethod function

– Davide Vitali
Mar 21 at 20:24












1 Answer
1






active

oldest

votes


















1














Your logic seems to work fine.



If you click the "tidy" button in your jsFiddle, you can see that you incorrectly nested the errorElement, errorPlacement, invalidHandler, submitHandler, highlight, and unhighlight options inside of messages.



These options are supposed to be siblings of messages and rules.



$("#myForm").validate(
rules:
....
,
messages:
....
,
errorElement: "em",
errorPlacement: function (error, element)
....
,
invalidHandler: function(form, validator)
....
,
highlight: function (element, errorClass, validClass)
....
,
unhighlight: function (element, errorClass, validClass)
....
,
submitHandler: function(form)
....

);


DEMO: jsfiddle.net/pey29j4n/2/



NOTE: I totally agree with Daniel. It makes no sense to present the user with invalid options in the first place, and it would be far easier to dynamically add/remove the option from the select.



Here is a very crude proof-of-concept:



$('#city').on('change', function() 
if ($(this).val() == '1')
$('#delivery option[value="1"]').remove();

);


Or you could disable the option by ghosting it out:



$('#city').on('change', function() 
var option = $('#delivery option[value="1"]');
if ($(this).val() == '1')
option.attr('disabled', true);
else
option.attr('disabled', false);

);





share|improve this answer

























  • Thank you. Indeed, presenting options that are not applicable to user is wrong. I managed to create jQuery code that hides and shows applicalble options based on user input.

    – Rikijs
    Mar 23 at 11:49











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55288409%2fvalidate-dependent-select-options-with-jquery-validation-plugin%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














Your logic seems to work fine.



If you click the "tidy" button in your jsFiddle, you can see that you incorrectly nested the errorElement, errorPlacement, invalidHandler, submitHandler, highlight, and unhighlight options inside of messages.



These options are supposed to be siblings of messages and rules.



$("#myForm").validate(
rules:
....
,
messages:
....
,
errorElement: "em",
errorPlacement: function (error, element)
....
,
invalidHandler: function(form, validator)
....
,
highlight: function (element, errorClass, validClass)
....
,
unhighlight: function (element, errorClass, validClass)
....
,
submitHandler: function(form)
....

);


DEMO: jsfiddle.net/pey29j4n/2/



NOTE: I totally agree with Daniel. It makes no sense to present the user with invalid options in the first place, and it would be far easier to dynamically add/remove the option from the select.



Here is a very crude proof-of-concept:



$('#city').on('change', function() 
if ($(this).val() == '1')
$('#delivery option[value="1"]').remove();

);


Or you could disable the option by ghosting it out:



$('#city').on('change', function() 
var option = $('#delivery option[value="1"]');
if ($(this).val() == '1')
option.attr('disabled', true);
else
option.attr('disabled', false);

);





share|improve this answer

























  • Thank you. Indeed, presenting options that are not applicable to user is wrong. I managed to create jQuery code that hides and shows applicalble options based on user input.

    – Rikijs
    Mar 23 at 11:49















1














Your logic seems to work fine.



If you click the "tidy" button in your jsFiddle, you can see that you incorrectly nested the errorElement, errorPlacement, invalidHandler, submitHandler, highlight, and unhighlight options inside of messages.



These options are supposed to be siblings of messages and rules.



$("#myForm").validate(
rules:
....
,
messages:
....
,
errorElement: "em",
errorPlacement: function (error, element)
....
,
invalidHandler: function(form, validator)
....
,
highlight: function (element, errorClass, validClass)
....
,
unhighlight: function (element, errorClass, validClass)
....
,
submitHandler: function(form)
....

);


DEMO: jsfiddle.net/pey29j4n/2/



NOTE: I totally agree with Daniel. It makes no sense to present the user with invalid options in the first place, and it would be far easier to dynamically add/remove the option from the select.



Here is a very crude proof-of-concept:



$('#city').on('change', function() 
if ($(this).val() == '1')
$('#delivery option[value="1"]').remove();

);


Or you could disable the option by ghosting it out:



$('#city').on('change', function() 
var option = $('#delivery option[value="1"]');
if ($(this).val() == '1')
option.attr('disabled', true);
else
option.attr('disabled', false);

);





share|improve this answer

























  • Thank you. Indeed, presenting options that are not applicable to user is wrong. I managed to create jQuery code that hides and shows applicalble options based on user input.

    – Rikijs
    Mar 23 at 11:49













1












1








1







Your logic seems to work fine.



If you click the "tidy" button in your jsFiddle, you can see that you incorrectly nested the errorElement, errorPlacement, invalidHandler, submitHandler, highlight, and unhighlight options inside of messages.



These options are supposed to be siblings of messages and rules.



$("#myForm").validate(
rules:
....
,
messages:
....
,
errorElement: "em",
errorPlacement: function (error, element)
....
,
invalidHandler: function(form, validator)
....
,
highlight: function (element, errorClass, validClass)
....
,
unhighlight: function (element, errorClass, validClass)
....
,
submitHandler: function(form)
....

);


DEMO: jsfiddle.net/pey29j4n/2/



NOTE: I totally agree with Daniel. It makes no sense to present the user with invalid options in the first place, and it would be far easier to dynamically add/remove the option from the select.



Here is a very crude proof-of-concept:



$('#city').on('change', function() 
if ($(this).val() == '1')
$('#delivery option[value="1"]').remove();

);


Or you could disable the option by ghosting it out:



$('#city').on('change', function() 
var option = $('#delivery option[value="1"]');
if ($(this).val() == '1')
option.attr('disabled', true);
else
option.attr('disabled', false);

);





share|improve this answer















Your logic seems to work fine.



If you click the "tidy" button in your jsFiddle, you can see that you incorrectly nested the errorElement, errorPlacement, invalidHandler, submitHandler, highlight, and unhighlight options inside of messages.



These options are supposed to be siblings of messages and rules.



$("#myForm").validate(
rules:
....
,
messages:
....
,
errorElement: "em",
errorPlacement: function (error, element)
....
,
invalidHandler: function(form, validator)
....
,
highlight: function (element, errorClass, validClass)
....
,
unhighlight: function (element, errorClass, validClass)
....
,
submitHandler: function(form)
....

);


DEMO: jsfiddle.net/pey29j4n/2/



NOTE: I totally agree with Daniel. It makes no sense to present the user with invalid options in the first place, and it would be far easier to dynamically add/remove the option from the select.



Here is a very crude proof-of-concept:



$('#city').on('change', function() 
if ($(this).val() == '1')
$('#delivery option[value="1"]').remove();

);


Or you could disable the option by ghosting it out:



$('#city').on('change', function() 
var option = $('#delivery option[value="1"]');
if ($(this).val() == '1')
option.attr('disabled', true);
else
option.attr('disabled', false);

);






share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 21 at 22:11

























answered Mar 21 at 21:48









SparkySparky

82.9k20152242




82.9k20152242












  • Thank you. Indeed, presenting options that are not applicable to user is wrong. I managed to create jQuery code that hides and shows applicalble options based on user input.

    – Rikijs
    Mar 23 at 11:49

















  • Thank you. Indeed, presenting options that are not applicable to user is wrong. I managed to create jQuery code that hides and shows applicalble options based on user input.

    – Rikijs
    Mar 23 at 11:49
















Thank you. Indeed, presenting options that are not applicable to user is wrong. I managed to create jQuery code that hides and shows applicalble options based on user input.

– Rikijs
Mar 23 at 11:49





Thank you. Indeed, presenting options that are not applicable to user is wrong. I managed to create jQuery code that hides and shows applicalble options based on user input.

– Rikijs
Mar 23 at 11:49



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55288409%2fvalidate-dependent-select-options-with-jquery-validation-plugin%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현