Adding functional capabilities to my jquery plugin

巧了我就是萌 提交于 2021-02-08 11:10:58

问题


I'm writing a jquery plugin. The purpose of the plugin is to scan a table with 1 row of inputs and create the capability to add new rows of similar inputs. Then, when any of those inputs are changed, the plugin will scan all the inputs in the table and generate a JSON string and put that string into a hidden input. I create the plugin with a line of code like this: jQuery("#reports").multiSubmit({ table : "reports", input : "reportSelections" });

Now, I need to add the capability to add a new row to the table. So, I need to do something like

jQuery("#reports").multiSubmit("ADD");

which will then call a function which will scan the HTML of the first row of the table and create a new row with the same inputs. How do I create new functions tied to a string in the plugin call?

Also, if there's a 3rd party plugin that will do something like this I'd like to look at it. Here's the current text of my plugin:

<script type = "text/javascript">
(function ( $ ) {

    $.fn.multiSubmit = function( options )
    {
        var tableNode = jQuery("#" + options.table);
        var inputNode = jQuery("#" + options.input);
        var numInputs = tableNode.find("input").length;
        var numSelects = tableNode.find("select").length;
        var totalInputs = numInputs + numSelects;

        //scan each row of inputs to construct a javascript Object, then put its JSON equivalent into the input
        function evaluateInputs()
        {
            var dataObject = [];
            var rows = tableNode.find("tbody").find("tr");
            for (var index = 0; index < rows.length; index++)
            {
                var row = $(rows.get(index));
                var rowObject = {};
                var inputs = row.find("select,input");
                for (var index2 = 0; index2 < inputs.length; index2++)
                {
                    var input = $(inputs.get(index2));
                    var name = input.attr("name");
                    rowObject[name] = input.val();
                }
                dataObject.push(rowObject);
            }
            inputNode.val(JSON.stringify(dataObject));
        }

        function attachHandlers()
        {
            var inputs = tableNode.find("input, select");
            console.log(inputs.length);
            for (var index = 0; index < inputs.length; index++)
            {
                var inputNode = $(inputs.get(index));
                inputNode.change(evaluateInputs);
            }
        }
        attachHandlers();
        return this;
    };
}( jQuery ));
$( document ).ready(function() {
    jQuery("#reports").multiSubmit({
        table : "reports",
        input : "reportSelections"
    });
});

</script>

来源:https://stackoverflow.com/questions/65243747/adding-functional-capabilities-to-my-jquery-plugin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!