jQuery:用特定类设置/重置表单字段(改进代码)

jQuery: set / reset form fields with certain class (improve code)

本文关键字:字段 表单 代码 设置 jQuery      更新时间:2023-09-26

我是jQuery新手,希望这里有人能帮助我。

我有一个大的HTML表单与隐藏div ('#requestDetails')。在这个div中有复选框、单选按钮和具有特定值('.hiddenDefault')的特定类的选择,用于仅在它们可见时应用默认值。

现在我有一个特定的事件显示这个div和另一个隐藏它。

当显示div时,我想设置上述默认值。
当隐藏它我想重置字段,包括该div内的所有输入字段(即取消选中/取消选择它们并删除任何默认值或输入值)。

我有下面的代码,这看起来对我第一眼,但我想知道这是适当的/有效的代码,如果我在这里错过了任何东西,如果有一个更好/更快的方法来实现相同的。

My jQuery:

$('[name=requestType]').on('change', function(){
    if($(this).hasClass('triggerDiv')){
        $('#requestDetails').find('.hiddenDefault').each(function(){
            // set default values + show div
            $(this).not('select').prop('checked', true);
            $(this).not('input[type=checkbox], input[type=radio]').prop('selected', true);
        });
        $('#requestDetails').show();
    }else{
        $('#requestDetails').find('input, select').each(function(){
            // empty / reset fields + hide div
            $(this).find('input[type=checkbox], input[type=radio]').prop('checked', false);
            $(this).find('input').not(':button, :checkbox, :hidden, :radio, :reset, :submit').val('');
            $(this).find('select').prop('selected', false);                     
        });
        $('#requestDetails').hide();
    }
});

提前感谢任何帮助与此,迈克

只是改进你写的代码的语法或风格:

$('[name=requestType]').on('change', function(){
    if($(this).hasClass('triggerDiv')){
        // show div + set default values
            $(this).not('select').prop('checked', true);
        $(this).not('input[type=checkbox], input[type=radio]').prop('selected', true);
            $('#requestDetails').show();
    }else{
        // hide div + reset fields
             $('#requestDetails').find('input[type=checkbox], input[type=radio], input, select').not(':button, :checkbox, :hidden, :radio, :reset, :submit').val('').prop('checked', false);             
             $('#requestDetails').hide();
    }
});

对不起没有检查语法,如果我错了请纠正我。这将提高性能,以及您在每个