onclick="this.form.submit();" 无法提交的解决办法

本文介绍了一种在网页中确保表单能够成功提交的方法。当使用 onclick=this.form.submit(); 无法正常工作时,可以通过指定表单名称来实现提交功能,即使用 onclick=document.forms['form_name'].submit();。此方法适用于多种浏览器环境。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

网页中 如果使用 onclick="this.form.submit();" 无法提交表达,可以使用下面的代码:
 

onclick="document.forms['form'].submit();" 
 

范例:
<form name="search" type="get">
        <input type="hidden" name="m" value="search"/>
  <input type="hidden" name="c" value="index"/>
  <input type="hidden" name="a" value="init"/>
  <input type="hidden" name="typeid" value="1" id="typeid"/>
  <input type="hidden" name="siteid" value="{$siteid}" id="siteid"/>
  <input type="text" class="csc_queryinput" id="q"  name="q" maxlength="30" value=""/>
  <div class="csc_querySubmit" 
onclick="document.forms['search'].submit();"><span>搜索</span></div>
</form>

转自:https://www.cnblogs.com/billybobby/p/6595517.html

<template> <div class="app-container"> <el-card class="box-card"> <div slot="header" class="clearfix"> <span>发起流程</span> </div> <el-col :span="18" :offset="3"> <div class="form-conf" v-if="formOpen"> <parser :key="new Date().getTime()" :form-conf="formData" @submit="submit" ref="parser" @getData="getData"/> </div> </el-col> </el-card> </div> </template> <script> import { getProcessForm, startProcess } from '@/api/workflow/process' import Parser from '@/utils/generator/parser' export default { name: 'WorkStart', components: { Parser }, data() { return { definitionId: null, deployId: null, procInsId: null, formOpen: false, formData: {}, } }, created() { this.initData(); }, methods: { initData() { this.deployId = this.$route.params && this.$route.params.deployId; this.definitionId = this.$route.query && this.$route.query.definitionId; this.procInsId = this.$route.query && this.$route.query.procInsId; getProcessForm({ definitionId: this.definitionId, deployId: this.deployId, procInsId: this.procInsId }).then(res => { if (res.data) { this.formData = res.data; this.formOpen = true } }) }, /** 接收子组件传的值 */ getData(data) { if (data) { const variables = []; data.fields.forEach(item => { let variableData = {}; variableData.label = item.__config__.label // 表单值为多个选项时 if (item.__config__.defaultValue instanceof Array) { const array = []; item.__config__.defaultValue.forEach(val => { array.push(val) }) variableData.val = array; } else { variableData.val = item.__config__.defaultValue } variables.push(variableData) }) this.variables = variables; } }, submit(data) { if (data && this.definitionId) { // 启动流程并将表单数据加入流程变量 startProcess(this.definitionId, JSON.stringify(data.valData)).then(res => { this.$modal.msgSuccess(res.msg); this.$tab.closeOpenPage({ path: '/work/own' }) }) } } } } </script> <style lang="scss" scoped> .form-conf { margin: 15px auto; width: 80%; padding: 15px; } </style> import { deepClone } from '@/utils/index'; import { getToken } from '@/utils/auth'; import render from '@/utils/generator/render'; import axios from 'axios' import Vue from 'vue'; Vue.prototype.$axios = axios const ruleTrigger = { 'el-input': 'blur', 'el-input-number': 'blur', 'el-select': 'change', 'el-radio-group': 'change', 'el-checkbox-group': 'change', 'el-cascader': 'change', 'el-time-picker': 'change', 'el-date-picker': 'change', 'el-rate': 'change', 'el-upload': 'change' } const layouts = { colFormItem(h, scheme) { const config = scheme.__config__ const listeners = buildListeners.call(this, scheme) let labelWidth = config.labelWidth ? `${config.labelWidth}px` : null if (config.showLabel === false) labelWidth = '0' return ( <el-col span={config.span}> <el-form-item label-width={labelWidth} prop={scheme.__vModel__} label={config.showLabel ? config.label : ''}> <render conf={scheme} on={listeners} /> </el-form-item> </el-col> ) }, rowFormItem(h, scheme) { let child = renderChildren.apply(this, arguments) if (scheme.type === 'flex') { child = <el-row type={scheme.type} justify={scheme.justify} align={scheme.align}> {child} </el-row> } return ( <el-col span={scheme.span}> <el-row gutter={scheme.gutter}> {child} </el-row> </el-col> ) } } function renderFrom(h) { const { formConfCopy } = this return ( <el-row gutter={formConfCopy.gutter}> <el-form size={formConfCopy.size} label-position={formConfCopy.labelPosition} disabled={formConfCopy.disabled} label-width={`${formConfCopy.labelWidth}px`} ref={formConfCopy.formRef} // model不能直接赋值 https://github.com/vuejs/jsx/issues/49#issuecomment-472013664 props={{ model: this[formConfCopy.formModel] }} rules={this[formConfCopy.formRules]} > {renderFormItem.call(this, h, formConfCopy.fields)} {formConfCopy.formBtns && formBtns.call(this, h)} </el-form> </el-row> ) } function formBtns(h) { return <el-col> <el-form-item size="large"> <el-button type="primary" onClick={this.submitForm}>提交</el-button> <el-button onClick={this.resetForm}>重置</el-button> </el-form-item> </el-col> } function renderFormItem(h, elementList) { return elementList.map(scheme => { const config = scheme.__config__ const layout = layouts[config.layout] if (layout) { return layout.call(this, h, scheme) } throw new Error(`没有与${config.layout}匹配的layout`) }) } function renderChildren(h, scheme) { const config = scheme.__config__ if (!Array.isArray(config.children)) return null return renderFormItem.call(this, h, config.children) } function setValue(event, config, scheme) { this.$set(config, 'defaultValue', event) this.$set(this[this.formConf.formModel], scheme.__vModel__, event) } function buildListeners(scheme) { const config = scheme.__config__ const methods = this.formConf.__methods__ || {} const listeners = {} // 给__methods__中的方法绑定this和event Object.keys(methods).forEach(key => { listeners[key] = event => methods[key].call(this, event) }) // 响应 render.js 中的 vModel $emit('input', val) listeners.input = event => setValue.call(this, event, config, scheme) return listeners } export default { components: { render }, props: { formConf: { type: Object, required: true } }, data() { const data = { formConfCopy: deepClone(this.formConf), [this.formConf.formModel]: {}, [this.formConf.formRules]: {} } this.initFormData(data.formConfCopy.fields, data[this.formConf.formModel]) this.buildRules(data.formConfCopy.fields, data[this.formConf.formRules]) return data }, methods: { initFormData(componentList, formData) { componentList.forEach(cur => { this.buildOptionMethod(cur) const config = cur.__config__; if (cur.__vModel__) { formData[cur.__vModel__] = config.defaultValue; // 初始化文件列表 if (cur.action && config.defaultValue) { cur['file-list'] = config.defaultValue; } } if (cur.action) { cur['headers'] = { Authorization: "Bearer " + getToken(), } cur['on-success'] = (res, file, fileList) => { formData[cur.__vModel__] = fileList; if (res.code === 200 && fileList) { config.defaultValue = fileList; fileList.forEach(val =>{ val.url = val.response.data.url; val.ossId = val.response.data.ossId; }) } }; // 点击文件列表中已上传的文件时的钩子 cur['on-preview'] = (file) => { this.$download.oss(file.ossId) } } if (config.children) { this.initFormData(config.children, formData); } }) }, // 特殊处理的 Option buildOptionMethod(scheme) { const config = scheme.__config__; if (config && config.tag === 'el-cascader') { if (config.dataType === 'dynamic') { this.$axios({ method: config.method, url: config.url }).then(resp => { var { data } = resp scheme[config.dataConsumer] = data[config.dataKey] }); } } }, buildRules(componentList, rules) { componentList.forEach(cur => { const config = cur.__config__ if (Array.isArray(config.regList)) { if (config.required) { const required = { required: config.required, message: cur.placeholder } if (Array.isArray(config.defaultValue)) { required.type = 'array' required.message = `请至少选择一个${config.label}` } required.message === undefined && (required.message = `${config.label}不能为空`) config.regList.push(required) } rules[cur.__vModel__] = config.regList.map(item => { item.pattern && (item.pattern = eval(item.pattern)) item.trigger = ruleTrigger && ruleTrigger[config.tag] return item }) } if (config.children) this.buildRules(config.children, rules) }) }, resetForm() { this.formConfCopy = deepClone(this.formConf) this.$refs[this.formConf.formRef].resetFields() }, submitForm() { this.$refs[this.formConf.formRef].validate(valid => { if (!valid) return false const params = { formData: this.formConfCopy, valData: this[this.formConf.formModel] } this.$emit('submit', params) return true }) }, // 传值给父组件 getData(){ debugger this.$emit('getData', this[this.formConf.formModel]) // this.$emit('getData',this.formConfCopy) } }, render(h) { return renderFrom.call(this, h) } } 现在我启动流程里面是没有提交按钮的,因为我的表单可能会有空的情况,我需要提交按钮
07-23
const {getModalConfig,registerModal} = require('../modal-registry/modal-registry'); Component({ properties: { show: { type: Boolean, value: false }, title: { type: String, value: '表单标题' }, config: { type: Array, value: [] }, formData: { type: Object, value: {} }, modalName: { type: String, value: '' }, initData: { type: null, value: null, } }, data: { parentParams: {}, tempData: {}, errors: {}, processedConfig: {}, loading: false }, observers: { 'show, modalName'(show, modalName) { show && modalName && this.loadModalConfig(modalName) } }, methods: { // 加载弹窗配置 async loadModalConfig(modalName) { this.setData({ loading: true }) try { let config = getModalConfig(modalName) if (!config) throw new Error(`未找到弹窗配置: ${modalName}`) // 处理前置逻辑 config = await this.processBeforeShow(config) this.setData({ processedConfig: config, loading: false }) } catch (error) { console.error('加载失败:', error) this.setData({ loading: false }) this.triggerEvent('error', { error }) } }, // 处理前置逻辑, 这段代码已经处理好了不用任何修改 async processBeforeShow(config) { const initData = this.properties.initData let processedConfig = { ...config }; if (initData) { if (Array.isArray(initData)) { // 处理数组类型 processedConfig.config = config.config.map((item, index) => index < initData.length ? { ...item, ...initData[index] } // 正确合并属性 : { ...item } // 超出部分保留原配置 ); return processedConfig; } else if (typeof initData === "object") { // 处理对象类型 processedConfig.config = config.config.map(configItem => { const key = configItem.field; return initData.hasOwnProperty(key) ? { ...configItem, ...initData[key] } // 直接属性访问 : { ...configItem }; }); return processedConfig; } } if (typeof config.beforeShow === 'function') { const beforeData = await config.beforeShow() processedConfig.config = config.config.map(configItem => { const key = configItem.field; return beforeData.hasOwnProperty(key) ? { ...configItem, ...beforeData[key] } // 直接属性访问 : { ...configItem }; }); return processedConfig; } return config }, // 表单验证 validateForm() { const errors = {}; this.data.processedConfig.config.forEach(item => { if (item.verify) { // 支持自定义验证函数 const isValid = item.verify( this.data.formData[item.field], item.field, this.data.formData ); if (isValid !== true) { errors[item.field] = typeof isValid === 'string' ? isValid : item.errorMessage || `${item.title}验证失败`; } } }); return errors; }, // 提交处理 async submitForm() { if (this.data.loading) return // 验证表单 const errors = this.validateForm() if (Object.keys(errors).length) { return this.setData({ errors }) } if (this.data.processedConfig.onSubmit) { await this.data.processedConfig.onSubmit(this.data.formData) this.setData({ loading: true }) this.closeModal() return; } try { this.setData({ loading: true }) // 触发提交事件 this.triggerEvent('submit', this.data.formData) this.closeModal() } finally { this.setData({ loading: false }) } }, // 关闭弹窗 closeModal() { this.setData({ show: false, processedConfig: [] }) this.triggerEvent('close') }, // 输入处理 handleInput(e) { const field = e.currentTarget.dataset.field; const value = e.detail.value || e.detail; this.setData({ [`formData.${field}`]: value, [`errors.${field}`]: '' }); // 触发字段级 change 事件 const item = this.findItemConfig(field, this.data.processedConfig.config); if (item && item.onChange) { item.onChange(value, field, this.data.formData); } this.triggerEvent('change', { field, value }); }, /** * 处理时间选择变化事件 * @param {Object} e - 事件对象 * @param {string} e.currentTarget.dataset.field - 表单字段名 * @param {string} e.detail.value - 选择的时间值 * @fires change - 触发change事件,传递字段名和值 */ handleTimeChange(e) { const { field } = e.currentTarget.dataset; const value = e.detail.value; this.setData({ [`formData.${field}`]: value, [`tempData.${field}_show`]: false }); this.triggerEvent('change', { field, value }); }, /** * 打开时间选择器 * @param {Object} e - 事件对象 * @param {string} e.currentTarget.dataset.field - 字段名 */ openTimePicker(e) { const { field } = e.currentTarget.dataset; this.setData({ [`tempData.${field}_show`]: true }); }, // 新增:关闭时间选择器 closeTimePicker(e) { const { field } = e.currentTarget.dataset; this.setData({ [`tempData.${field}_show`]: false }); }, // 在custom-form-modal/index.js的methods中添加 handleSelectChange(e) { const { field } = e.currentTarget.dataset; const value = e.detail.value; this.setData({ [`formData.${field}`]: value, [`errors.${field}`]: '' }); // 触发字段级change事件 const item = this.findItemConfig(field); if (item && item.onChange) { item.onChange(value, field, this.data.formData); } this.triggerEvent('change', { field, value }); }, // 查找按钮配置 findItemConfig(field) { // processedConfig.config 是一维数组,直接遍历 for (const item of this.data.processedConfig.config) { if (item.field === field && item.button) { return item.button; } } return null; }, /** * 处理自定义事件 * @param {Object} e - 事件对象 * @param {string} e.detail.field - 字段名 * @param {Object} e.detail.event - 事件详情 * @fires customEvent - 触发自定义事件 */ handleCustomEvent(e) { const { field, event } = e.detail; this.triggerEvent('customEvent', { field, ...event }); }, // 打开子窗口的统一方法 /** * 打开子模态框 * @param {string} childModalName - 子模态框名称 * @param {Object} [initData={}] - 初始化数据 * @param {string|null} [sourceField=null] - 触发子窗口的字段名 * @description 保存当前模态框状态到parentParams,并初始化子模态框状态 */ openChildModal(childModalName, initData = {}, sourceField = null) { // 保存当前状态到parentParams const parentParams = { modalName: this.properties.modalName, formData: this.data.formData, tempData: this.data.tempData, errors: this.data.errors, config: this.data.processedConfig, sourceField: sourceField // 记录触发子窗口的字段 }; // 设置新的弹窗状态 this.setData({ modalName: childModalName, parentParams: parentParams, formData: this.getChildInitData(childModalName, initData, sourceField), tempData: {}, errors: {}, processedConfig: {} }); }, // 获取子窗口初始数据 getChildInitData(childModalName, initData, sourceField) { // 默认初始化空对象 if (!initData) return {}; // 支持三种初始化方式: // 1. 函数方式:动态生成数据 if (typeof initData === 'function') { return initData(this.data.formData, sourceField); } // 2. 字符串方式:从父表单获取指定字段 if (typeof initData === 'string') { return this.data.formData[initData] || {}; } // 3. 对象方式:直接使用传入的对象 return initData; }, // 关闭当前弹窗(可能恢复父窗口) closeModal(result = null) { // 如果有父级参数,恢复父窗口 if (this.data.parentParams) { const parentParams = this.data.parentParams; // 处理子窗口返回结果 if (result !== null && parentParams.sourceField) { this.handleChildResult(parentParams.sourceField, result); } // 恢复父窗口状态 this.setData({ modalName: parentParams.modalName, formData: parentParams.formData, tempData: parentParams.tempData, errors: parentParams.errors, processedConfig: parentParams.config, parentParams: parentParams.parentParams // 保持嵌套结构 }); } else { // 没有父级参数,完全关闭弹窗 this.setData({ show: false, modalName: '', processedConfig: {} }); this.triggerEvent('close', result); } }, // 修改后的按钮点击处理 handleButtonClick(e) { const { field } = e.currentTarget.dataset; const itemConfig = this.findItemConfig(field); if (!itemConfig) return; // 优先执行onClick回调 if (itemConfig.onClick) { itemConfig.onClick(); return; } if (itemConfig.childModal) { // 处理动态childData const initData = typeof itemConfig.childData === 'function' ? itemConfig.childData(this.data.formData) : itemConfig.childData || {}; this.openChildModal( itemConfig.childModal, initData, field ); } else { this.triggerEvent('buttonClick', { field }); } } , // 处理子窗口结果// 增强子窗口结果处理 handleChildResult(field, result) { // 通用结果处理器 switch (field) { case 'add_child': // 处理数组类型字段追加 this.setData({ [`formData.${field}`]: [ ...(this.data.formData[field] || []), result ] }); break; case 'edit_item': // 处理数组索引更新 const index = this.data.editingIndex; this.setData({ [`formData.${field}[${index}]`]: result }); break; default: // 通用字段更新 if (Array.isArray(this.data.formData[field])) { // 数组字段替换整个数组 this.setData({ [`formData.${field}`]: result }); } else { // 对象字段合并 this.setData({ [`formData.${field}`]: { ...this.data.formData[field], ...result } }); } } // 触发更新事件 this.triggerEvent('change', { field, value: result }); } , } }) 传进来的初始数据如果是对象,之中的建没在配置中找到匹配项,直接把该键值对合并到提交数据中
最新发布
08-05
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值