提问者:小点点

Javascript onclick函数停止HTML5的工作


日安,

我正在处理一个表单,其中我所有的文本字段都有一个必需的属性;我注意到,当我点击提交必需的属性时,不会显示弹出窗口来验证字段是否为空。

我的页面上有两个提交按钮,都使用onclick submitform函数;一个打开一个新选项卡,另一个提交表单并转到一个新页面。

出于调试目的,我删除了打开新选项卡的按钮,并删除了第二个按钮上的onclick属性,它就工作了;我在谷歌上搜索了一整天,但似乎找不到与目前相同的情景。

我相信这与我的JS有关,但我不确定在我的代码中添加或删除什么;请看下面我的代码。

JavaScript

 function submitForm(action,newtab)
 {
    document.getElementById('add2').target = newtab ? '_blank' : '_self';
    document.getElementById('add2').action = action;
    document.getElementById('add2').submit();
 }

超文本标记语言

 <form id="add2" action="add5.php" method="post">
 <input placeholder="First Name" tabindex="1"
 name="fname" maxlength="128" size="30" required>
 <input placeholder="Last Name" tabindex="12"
 name="lname" maxlength="128" size="30" required>
 <button tabindex="3" value="Save"
 name="save" onclick="submitForm('add3.php',1);" 
 type="submit">Child Information</button>
 <button tabindex="4" value="Save"
 name="save" onclick="submitForm('add5.php',0);" 
 type="submit">Save Details</button>
 </form>

我有一个按钮属性,但我已将其设置为type="提交",我很确定这是可行的,因为我已经测试过了,当我删除onhtml功能;我的问题是,我可以在不删除JavaScript的onhtml功能的情况下工作所需的属性吗?

任何帮助都非常感谢。


共3个答案

匿名用户

我找到了问题的答案,问题是我将onClick方法绑定到submit。onClick将首先触发,这将导致它通过验证器。

解决方案是在HTML代码中将onClick改为onSubmit。

<button tabindex="3" value="Save"
name="save" onsubmit="submitForm('add3.php',1);" 
type="submit">Child Information</button>
<button tabindex="4" value="Save"
name="save" onsubmit="submitForm('add5.php',0);" 
type="submit">Save Details</button>

匿名用户

在提交onclick函数之前,只需对表单使用“checkValidity()”方法,如下所示:

if($("#add2").checkValidity()) { 
 document.getElementById('add2').submit();
}

看这把小提琴:http://jsfiddle.net/36uv2e52/33/

匿名用户

您不必使用required,只需在提交前检查值即可。

function submitForm(action,newtab) {
    fname = document.getElementById('fname').value;
    lname = document.getElementById('lname').value;
    if (fname == "" || lname == "") {
        alert("First and last name are required");
        exit;
    } else {
        document.getElementById('add2').target = newtab ? '_blank' : '_self';
        document.getElementById('add2').action = action;
        document.getElementById('add2').submit();
    }
 }