草庐IT

关于jquery:BeforeSubmit

codeneng 2023-03-28 原文

BeforeSubmit & ClearAfterAdd Events not firing

我调整了这个链接本地表单编辑演示和 jqGrid 4.4.1 以适应我的解决方案,但是我更改了 CloseAfterAdd:false 并添加了 ClearAfterAdd:truebeforeSubmit: CheckValid。但是,这两个事件都没有触发以实现我的目标。我的目标是在使用回车键作为保存键添加记录时保持对话框表单打开,并在保存后清除表单。其次验证 CheckValid 函数中的一组相关字段。请有人指出我做错了什么。谢谢

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
function checkvalue(value, colname) { alert(value || colname); return [true,""]; }
        var vlcontractor, field2, field3, field4, vlBuckid, vlHospid, myCustomCheck, myCustomCheck2;
        myCustomCheck = function (value, colname) {
            switch (colname) {
                case 'Contractor':
                    vlcontractor = value;
                    break;
                case 'Company Name':
                    field2 = value;
                    break;
                case 'Project End Date':
                    field3 = value;
                    break;
                default:
                    break;
            }

            if (vlcontractor =="Yes" && (field2 == undefined || field3 == undefined))
            { return [false,"Company/State ID/End Date is needed for a Contractor"]; }

            if (vlcontractor != undefined  && field2 != undefined) {
                // validate the fields here
                return [false,"some error text"];
            } else {
                //alert('we are good');
                return [true];
            }
        };
        myCustomCheck2 = function (value, colname) {
            switch (colname) {
                case 'BUCK ID':
                    vlBuckid = value;
                    break;
                case 'Hospital ID':
                    vlHospid = value;
                    break;
            }
            if ((vlBuckid == undefined && vlHospid == undefined) || (vlBuckid == '' && vlHospid == ''))
            { return [false,"A BuckID or Hospital ID is required."]; }
            else { return [true]; }
        }

        $(function () {
            var lastSel,
            mydata = '',
                grid = $("#list"),
                getColumnIndex = function (columnName) {
                    var cm = $(this).jqGrid('getGridParam', 'colModel'), i, l = cm.length;
                    for (i = 0; i < l; i++) {
                        if ((cm[i].index || cm[i].name) === columnName) {
                            return i; // return the colModel index
                        }
                    }
                    return -1;
                },
                CheckValid = function (postdata, formid) {
                    alert(postdata);
                    return false;
                },
                onclickSubmitLocal = function (options, postdata) {
                    var $this = $(this), grid_p = this.p,
                        idname = grid_p.prmNames.id,
                        grid_id = this.id,
                        id_in_postdata = grid_id +"_id",
                        rowid = postdata[id_in_postdata],
                        addMode = rowid ==="_empty",
                        oldValueOfSortColumn,
                        new_id,
                        tr_par_id,
                        colModel = grid_p.colModel,
                        cmName,
                        iCol,
                        cm;

                    // postdata has row id property with another name. we fix it:
                    if (addMode) {
                        // generate new id
                        new_id = $.jgrid.randId();
                        while ($("#" + new_id).length !== 0) {
                            new_id = $.jgrid.randId();
                        }
                        postdata[idname] = String(new_id);
                    } else if (typeof postdata[idname] ==="undefined") {
                        // set id property only if the property not exist
                        postdata[idname] = rowid;
                    }
                    delete postdata[id_in_postdata];

                    // prepare postdata for tree grid
                    if (grid_p.treeGrid === true) {
                        if (addMode) {
                            tr_par_id = grid_p.treeGridModel === 'adjacency' ? grid_p.treeReader.parent_id_field : 'parent_id';
                            postdata[tr_par_id] = grid_p.selrow;
                        }

                        $.each(grid_p.treeReader, function (i) {
                            if (postdata.hasOwnProperty(this)) {
                                delete postdata[this];
                            }
                        });
                    }

                    // decode data if there encoded with autoencode
                    if (grid_p.autoencode) {
                        $.each(postdata, function (n, v) {
                            postdata[n] = $.jgrid.htmlDecode(v); // TODO: some columns could be skipped
                        });
                    }

                    // save old value from the sorted column
                    oldValueOfSortColumn = grid_p.sortname ==="" ? undefined : grid.jqGrid('getCell', rowid, grid_p.sortname);

                    // save the data in the grid
                    if (grid_p.treeGrid === true) {
                        if (addMode) {
                            $this.jqGrid("addChildNode", new_id, grid_p.selrow, postdata);
                        } else {
                            $this.jqGrid("setTreeRow", rowid, postdata);
                        }
                    } else {
                        if (addMode) {
                            // we need unformat all date fields before calling of addRowData
                            for (cmName in postdata) {
                                if (postdata.hasOwnProperty(cmName)) {
                                    iCol = getColumnIndex.call(this, cmName);
                                    if (iCol >= 0) {
                                        cm = colModel[iCol];
                                        if (cm && cm.formatter ==="date") {
                                            postdata[cmName] = $.unformat.date.call(this, postdata[cmName], cm);
                                        }
                                    }
                                }
                            }
                            $this.jqGrid("addRowData", new_id, postdata, options.addedrow);
                        } else {
                            $this.jqGrid("setRowData", rowid, postdata);
                        }
                    }

                    if ((addMode && options.closeAfterAdd) || (!addMode && options.closeAfterEdit)) {
                        // close the edit/add dialog
                        $.jgrid.hideModal("#editmod" + grid_id, {
                            gb:"#gbox_" + grid_id,
                            jqm: options.jqModal,
                            onClose: options.onClose
                        });
                    }

                    if (postdata[grid_p.sortname] !== oldValueOfSortColumn) {
                        // if the data are changed in the column by which are currently sorted
                        // we need resort the grid
                        setTimeout(function () {
                            $this.trigger("reloadGrid", [{ current: true}]);
                        }, 100);
                    }

                    // !!! the most important step: skip ajax request to the server
                    options.processing = true;
                    $('#gridData').val(JSON.stringify(grid_p.data));
                    return {};
                },
                editSettings = {
                    //recreateForm: true,
                    jqModal: false,
                    reloadAfterSubmit: false,
                    closeOnEscape: true,
                    savekey: [true, 13],
                    closeAfterEdit: true,
                    beforeSubmit: CheckValid,
                    onclickSubmit: onclickSubmitLocal
                },
                addSettings = {
                    //recreateForm: true,
                    jqModal: false,
                    beforeSubmit: CheckValid,
                    reloadAfterSubmit: false,
                    savekey: [true, 13],
                    closeOnEscape: true,
                    closeAfterAdd: true,
                    clearAfterAdd: true,
                    onclickSubmit: onclickSubmitLocal
                },
                delSettings = {
                    // because I use"local" data I don't want to send the changes to the server
                    // so I use"processing:true" setting and delete the row manually in onclickSubmit
                    onclickSubmit: function (options, rowid) {
                        var $this = $(this), grid_id = $.jgrid.jqID(this.id), grid_p = this.p,
                            newPage = grid_p.page;

                        // reset the value of processing option to true to
                        // skip the ajax request to 'clientArray'.
                        options.processing = true;

                        // delete the row
                        $this.jqGrid("delRowData", rowid);
                        if (grid_p.treeGrid) {
                            $this.jqGrid("delTreeNode", rowid);
                        } else {
                            $this.jqGrid("delRowData", rowid);
                        }
                        $.jgrid.hideModal("#delmod" + grid_id, {
                            gb:"#gbox_" + grid_id,
                            jqm: options.jqModal,
                            onClose: options.onClose
                        });

                        if (grid_p.lastpage > 1) {// on the multipage grid reload the grid
                            if (grid_p.reccount === 0 && newPage === grid_p.lastpage) {
                                // if after deliting there are no rows on the current page
                                // which is the last page of the grid
                                newPage--; // go to the previous page
                            }
                            // reload grid to make the row from the next page visable.
                            $this.trigger("reloadGrid", [{ page: newPage}]);
                        }

                        return true;
                    },
                    processing: true
                },
                initDateEdit = function (elem) {
                    setTimeout(function () {
                        $(elem).datepicker({
                            dateFormat: 'dd-M-yy',
                            //autoSize: true,
                            showOn: 'button',
                            changeYear: true,
                            changeMonth: true,
                            showButtonPanel: true,
                            showWeek: true
                        });
                    }, 100);
                },
                initDateSearch = function (elem) {
                    setTimeout(function () {
                        $(elem).datepicker({
                            dateFormat: 'dd-M-yy',
                            //autoSize: true,
                            //showOn: 'button', // it dosn't work in searching dialog
                            changeYear: true,
                            changeMonth: true,
                            showButtonPanel: true,
                            showWeek: true
                        });
                    }, 100);
                };
            grid.jqGrid({
                datatype: 'local',
                data: mydata,
                //colNames: [/*'Inv No', */'Client', 'Date', 'Amount', 'Tax', 'Total', 'Closed', 'Shipped via', 'Notes'],
                colNames: ['Emp/Stu ID', 'Last Name, First Name', 'BUCK ID', 'Hospital ID', 'Contractor', 'Company-Name', 'State ID', 'Project End Date'],
                colModel: [
                        { name: 'empstuid', index: 'empstuid', editable: true, width: 80, editrules: { required: false }, editoptions: { maxlength: 10 } },
                        { name: 'lastFirst', index: 'lastFirst', editable: true, width: 180, editrules: { required: true} },
                        { name: 'buckid', index: 'buckid', editable: true, width: 120, editrules: { custom: true, custom_func: myCustomCheck2 } },
                        { name: 'hospid', index: 'hospid', editable: true, width: 120, editrules: { custom: true, custom_func: myCustomCheck2 } },
                        {
                            name: 'contractor', index: 'contractor', editable: true, edittype: 'checkbox',
                            editoptions: { value:"Yes:No" }, width: 70, editrules: { custom: true, custom_func:myCustomCheck }
                        },
                        { name: 'compname', index: 'compname', editable: true, width: 110, editrules: { custom: true, custom_func:myCustomCheck } },
                        { name: 'stateid', index: 'stateid', editable: true, width: 80, editrules: { custom: true, custom_func: myCustomCheck } },
                        { name: 'enddate', index: 'enddate', editable: true, width: 110, editrules: { custom: true, custom_func: myCustomCheck } }
                ],
                altRows: true,
                rowNum: 10,
                rowList: [10, 20],
                pager: '#pager',
                gridview: true,
                rownumbers: true,
                autoencode: true,
                ignoreCase: true,
                sortname: 'invdate',
                viewrecords: true,
                sortorder: 'desc',
                footerrow: true,
                emptyrecords:"There are **no records added",
                caption: '',
                height: '100%',
                editurl: 'clientArray',
                ondblClickRow: function (rowid, ri, ci) {
                    var $this = $(this), p = this.p;
                    if (p.selrow !== rowid) {
                        // prevent the row from be unselected on double-click
                        // the implementation is for"multiselect:false" which we use,
                        // but one can easy modify the code for"multiselect:true"
                        $this.jqGrid('setSelection', rowid);
                    }
                    $this.jqGrid('editGridRow', rowid, editSettings);
                },
                onSelectRow: function (id) {
                    if (id && id !== lastSel) {
                        // cancel editing of the previous selected row if it was in editing state.
                        // jqGrid hold intern savedRow array inside of jqGrid object,
                        // so it is safe to call restoreRow method with any id parameter
                        // if jqGrid not in editing state
                        if (typeof lastSel !=="undefined") {
                            $(this).jqGrid('restoreRow', lastSel);
                        }
                        lastSel = id;
                    }
                }
            }).jqGrid('navGrid', '#pager', {edit:false,add:true, del:true, search:false, refresh:false}, editSettings, addSettings, delSettings,
                { multipleSearch: true, overlay: false,
                    onClose: function (form) {
                        // if we close the search dialog during the datapicker are opened
                        // the datepicker will stay opened. To fix this we have to hide
                        // the div used by datepicker
                        $("div#ui-datepicker-div.ui-datepicker").hide();
                    }
                });

回调 beforeSubmit 确实被触发,但仅在成功验证的情况下。

您使用自定义验证的方式是错误的。例如,如果您检查 contractor 值,如果公司已满,您将收到 "Company/State ID/End Date is needed for a Contractor" 错误消息事件。问题是您在 'compname' 列验证期间在 myCustomCheck 内部设置的变量 field2 将在 'contractor' 验证后设置,其中将使用 field2

如果您需要实现多个字段的自定义验证,您最好使用 beforeCheckValues 回调。回调将在所有其他验证之前调用。它得到所有字段作为输入的 postdata 。因此,您可以轻松验证数据。回调可以没有任何 return(或使用没有任何值的 return;)。您可以为一列添加具有 custom: true, custom_func 的验证规则。如果在 beforeCheckValues 回调中发现验证错误,您可以在验证函数内部返回 [false, errorMessage]

此外,我不建议您在 $(function () {...}); 之外声明任何函数或变量。您应该将所有代码放在其中。这样你会减少全局变量的数量。

有关关于jquery:BeforeSubmit的更多相关文章

  1. jquery - 我的 jquery AJAX POST 请求无需发送 Authenticity Token (Rails) - 2

    rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送

  2. jquery - 如何将 AJAX 变量从 jQuery 传递到他们的 Controller ? - 2

    我有一个电子邮件表格。但是我正在制作一个测试电子邮件表单,用户可以在其中添加一个唯一的电子邮件,并让电子邮件测试将其发送到该特定电子邮件。为了简单起见,我决定让测试电子邮件通过ajax执行,并将整个内容粘贴到另一个电子邮件表单中。我不知道如何将变量从我的HAML发送到我的Controllernew.html.haml-form_tagadmin_email_blast_pathdoSubject%br=text_field_tag'subject',:class=>"mass_email_subject"%brBody%br=text_area_tag'message','',:nam

  3. ruby-on-rails - 关于 Ruby 的一般问题 - 2

    我在我的rails应用程序中安装了来自github.com的acts_as_versioned插件,但有一段代码我不完全理解,我希望有人能帮我解决这个问题class_eval我知道block内的方法(或任何它是什么)被定义为类内的实例方法,但我在插件的任何地方都找不到定义为常量的CLASS_METHODS,而且我也不确定是什么here,并且有问题的代码从lib/acts_as_versioned.rb的第199行开始。如果有人愿意告诉我这里的内幕,我将不胜感激。谢谢-C 最佳答案 这是一个异端。http://en.wikipedia

  4. ruby - 我怎样才能更好地了解/了解更多关于 Ruby 的知识? - 2

    按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visitthehelpcenter指导。关闭9年前。我最近开始学习Ruby,这是我的第一门编程语言。我对语法感到满意,并且我已经完成了许多只教授相同基础知识的教程。我已经写了一些小程序(包括我自己的数组排序方法,在有人告诉我谷歌“冒泡排序”之前我认为它非常聪明),但我觉得我需要尝试更大更难的东西来理解更多关于Ruby.关于如何执行此操作的任何想法?

  5. ruby - 关于 Ruby 中 Dir[] 和 File.join() 的混淆 - 2

    我在Ruby中遇到了一个关于Dir[]和File.join()的简单程序,blobs_dir='/path/to/dir'Dir[File.join(blobs_dir,"**","*")].eachdo|file|FileUtils.rm_rf(file)ifFile.symlink?(file)我有两个困惑:首先,File.join(@blobs_dir,"**","*")中的第二个和第三个参数是什么意思?其次,Dir[]在Ruby中有什么用?我只知道它等价于Dir.glob(),但是,我对Dir.glob()确实不是很清楚。 最佳答案

  6. elasticsearch源码关于TransportSearchAction【阶段三】 - 2

    1.回顾.TransportServicepublicclassTransportServiceextendsAbstractLifecycleComponentTransportService:方法:1publicfinalTextendsTransportResponse>voidsendRequest(finalTransport.Connectionconnection,finalStringaction,finalTransportRequestrequest,finalTransportRequestOptionsoptions,TransportResponseHandlerT>

  7. 关于Qt程序打包后运行库依赖的常见问题分析及解决方法 - 2

    目录一.大致如下常见问题:(1)找不到程序所依赖的Qt库version`Qt_5'notfound(requiredby(2)CouldnotLoadtheQtplatformplugin"xcb"in""eventhoughitwasfound(3)打包到在不同的linux系统下,或者打包到高版本的相同系统下,运行程序时,直接提示段错误即segmentationfault,或者Illegalinstruction(coredumped)非法指令(4)ldd应用程序或者库,查看运行所依赖的库时,直接报段错误二.问题逐个分析,得出解决方法:(1)找不到程序所依赖的Qt库version`Qt_5'

  8. jquery - 如何在 rails 3.1 上安装 jQuery - 2

    我以为它已经安装了,但在我的gemfile中有gem"jquery-rails"但是在我的asset/javascripts文件夹中accounts.js.coffeeapplication.js都被注释掉了这是我的虚拟railsapplication但是在源代码中没有jQuery并且删除链接不起作用......任何想法都丢失了 最佳答案 看看thisRailscast.您可能需要检查application.js文件并确保它包含以下语句。//=requirejquery//=requirejquery_ujs

  9. jquery - Rails 如何创建 Jquery flash 消息而不是默认的 Rails 消息 - 2

    我想在页面顶部创建自定义Jquery消息而不是标准RailsFlash消息。我想在我的投票底部附近创建一条即时消息。我的Controller:defvote_up@post=Post.find(params[:id])current_user.up_vote(@post)flash[:message]='Thanksforvoting!'redirect_to(root_path,:notice=>'Takforditindlæg,deternuonline!')rescueMakeVoteable::Exceptions::AlreadyVotedErrorflash[:error]

  10. javascript - jQuery 的 jquery-1.10.2.min.map 正在触发 404(未找到) - 2

    我看到有关未找到文件min.map的错误消息:GETjQuery'sjquery-1.10.2.min.mapistriggeringa404(NotFound)截图这是从哪里来的? 最佳答案 如果ChromeDevTools报告.map文件的404(可能是jquery-1.10.2.min.map、jquery.min.map或jquery-2.0.3.min.map,但任何事情都可能发生)首先要知道的是,这仅在使用DevTools时才会请求。您的用户不会遇到此404。现在您可以修复此问题或禁用sourcemap功能。修复:获取文

随机推荐