在表单提交时加载 jquery 函数,而不是在更改事件上加载


Loading a jquery function on form submit instead on change event

我有一个动态更改菜单select jQuery脚本。该脚本populate()每次在其中一个菜单中发生更改事件时使用该函数。我希望在提交form后运行相同的脚本。要有一个想法,这就是脚本的样子......

$(document).ready(function(){
    function getUrlVars() {
        var vars = {};
        var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
            vars[key] = value;
        });
        return vars;
    }
    function populate() {
        if ($('#STATEID').val() == 'AK' || $('#OB_USTATEID').val() == 'DC') {
            // Alaska and District Columbia have no counties
            $('#county_drop_down3').hide();
            $('#no_county_drop_down3').show();
        } 
        else {
            fetch.doPost('../../getCounties2c.php');
        }
    }
    $('#STATEID').change(populate);
    var fetch = function() {
        var counties = $('#countyid');
        return {
            doPost: function(src) {
                $('#loading_county_drop_down3').show(); // Show the Loading...
                $('#county_drop_down3').hide(); // Hide the drop down
                $('#no_county_drop_down3').hide(); // Hide the "no counties" message (if it's the case)
                if (src) 
                    $.post(src, { state_code3: $('#STATEID').val() },  this.getCounties);
                else 
                    throw new Error('No SRC was passed to getCounties!');
            },
            getCounties: function(results) {
                if (!results) 
                    return;
                var allCities = $("<option value='"All'">All Counties</option>");
                counties.html(results);
                counties.prepend(allCities);
                var first = getUrlVars()["countyid"];
                if (first) { 
                    counties.val(first).attr('selected',true);
                }
                else {
                    counties.val("All").attr('selected',true);
                }
                $('#loading_county_drop_down3').hide(); // Hide the Loading...
                $('#county_drop_down3').show(); // Show the drop down
            }
        }
    }();
    populate();
}); 

我怎样才能做到这一点?任何建议将不胜感激!

使用 $(element).submit(function (e) {} ); 捕获提交事件。您甚至可以通过调用 $(element).submit() 来触发它。

j查询文档 : http://api.jquery.com/submit/