简体   繁体   中英

jQuery custom validator method getting called whenever element changes

I have a select which is the target of a custom validator method.

validator:

    var validator = $("#myform").validate({
        rules : {
            source: "source_selected",
        },
        messages : {
        },
        errorLabelContainer: $("#error_container ul"), 
        errorContainer: $("#error_container"), 
        wrapper : "li"      
     });

custom validator method:

    $.validator.addMethod("source_selected", function(value, element) {
        var source_id = $(element).selectedValues();
        if(source_id == 0) {
             return false;
        }

        return true;
    }, "Please a select a source to Copy subscriptions from.");

select:

<select name="source" id="source">
    <option value="0">-- Choose --</option>
    <? foreach($managers as $id => $name) { ?>
    <option value="<?=$id?>"><?=$name?></option>
    <? } ?>
</select>

Everytime I change the option in the select the source_selected function gets called. If I put an alert in there it gets triggered everytime I click out of the select box (similar to.blur). I want it to only be called when the submit button gets called.

submit click event:

    $("#submit_button").click(function() { 
        var valid = validator.form();
        if (valid) {
            document.myform.submit();
        }
    });

Any thoughts are greatly appreciated.

Instead of doing it as a validator - which seems useless for you - just call your validation function in the onSubmit, and check the return value of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM