dousui3124 2016-06-25 13:20
浏览 91
已采纳

一个表单中的输入字段是一个提交按钮所需的,但不适用于其他表单?

How can I differentiate two separate actions for my submit buttons in one form, whereas one SAVES data into database (as is), and other submits form as a valid request, >>but<< according to HTML5 native validation (I use "required" attributes in HTML form)?

My form has 66 fields and I don't want to validate them all in PHP AFTER submission (as it's too cumbersome and time consuming), or validate them all in JS BEFORE submission (as I am not that agile in JS, as in PHP), so I use "required" and "type" attributes in HTML5, which is very convenient and quite versatile way of validation (besides older browsers). However I cannot find a easy way to bypass the "required" attribute, when using save button, but not using "Send for submission" button. Can you help suggest a solution? I guess the prefered way is some JS/jQuery way, as I cannot determine which button would be used before hitting the button (so that I can make a field required or not).

Sample code:

<form>
A: <input type="text" name="A" required />
B: <input type="text" name="B" required />
C: <input type="text" name="C" />
<input type="submit" name="save" value="Save"> <!--do not require anything-->
<input type="submit" name="send" value="Send  for submission"> <!-- require everything-->
</form>

Of course my form is huge, as it has 66 fields, so best solutions here are possibly general and versatile.

  • 写回答

3条回答 默认 最新

  • doulin2555 2016-06-27 18:14
    关注

    I've eventually come up with something like this. HTML:

    <input type="submit" name="save" value="Save" onClick="removeRequired(this.form)">
    

    JS (using jQuery):

    function removeRequired(form){
        $.each(form, function(key, value) {
            if ( value.hasAttribute("required")){
                value.removeAttribute("required");
            }
        });
    }
    

    This is tested and working. It has this nice property, that I can keep the function elsewhere in files, to not clutch the php/html that is executing it. Only improvement I'd like (and probably other would be interested in) would be to eliminate jQuery as it's only used for browsing each input element in form, which seems easy enough for pure JS. However I could not find an easy way, and run out of time and used above with jQuery. Thanks

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出