在表单上加载jquery函数而不是在change事件上

时间:2012-05-30 20:13:58

标签: php jquery

我有一个动态更改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();
}); 

我怎样才能做到这一点?任何建议将受到高度赞赏!

1 个答案:

答案 0 :(得分:1)

使用$(element).submit(function (e) {} );来捕获提交事件。你甚至可以通过拨打$(element).submit()来解雇它。

jQuery docs:http://api.jquery.com/submit/