javascript - prevent validaton onfocusout depending of the radio button -


i'm having problem validate form below.
main issue have use "onfocusout" function validate inputs.
name input has required depending of radio selection.
when "value3" selected, focus set input.
while on input, if user tries change radio button, onfocusout triggered before radio value changed, , in case error shown while should not suggestion?

<form id="myform">        <input type="radio" name="radio" value="value1" /> value1   <input type="radio" name="radio" value="value2" /> value2   <input type="radio" name="radio" value="value3" /> value3    <input type="text" name="name" />    <input type="submit" /> </form>     

the js code is:

$("#myform").validate({     rules: {         name: {             required: {                 depends: function () {                     return $("input[name='radio']:checked").val() == "value3";                 }             }         }     },     messages: {         name: {             required: "you must enter name"         }     },     onfocusout: function (element) {         this.element(element);     },     submithandler: function (form) {         alert('success');         return false;     } });  $("input[name='radio']").change(function () {     var value = $(this).val();     if (value == "value3") $("input[name='name']").focus();     else $("input[name='name']").valid(); }); 

jsfiddle: http://jsfiddle.net/954ros6l/

you calling .valid() method late. call every time change radio buttons , timing correct.

$("input[name='radio']").on('change', function () {     $("input[name='name']").valid();  // <- move here     var value = $(this).val();     if (value == "value3") {         $("input[name='name']").focus();     } }); 

plus, if notice, validation message correctly appears when field invalid.

you not need custom onfocusout handler.

demo: http://jsfiddle.net/954ros6l/4/


sidenote:

you cannot use event.preventdefault() inside callback function since event not valid argument function. besides, .preventdefault() meant block default action of event, stopping page jump after anchor click, etc. ... not default behavior of plugin.

to change default behavior of onfocusout means write function override plugin's default behavior, you've done.


Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -