Window.confirm和html表单

时间:2014-03-29 04:00:07

标签: javascript html

我有这个表格

<form name="frm" action="users.jsp/manage-users?status=delete&index=1" method="POST">
    <button value="delete" name="btn" onclick="if(window.confirm('Delete user?\nWARNING! THIS IS ACTION CANNOT BE UNDONE!'))
{document.frm.submit();}">
    Delete
    </button>
</form>

当我按下取消时,它仍然提交。我做错了什么?

3 个答案:

答案 0 :(得分:2)

您需要return false;

<form name="frm" action="users.jsp/manage-users?status=delete&index=1" method="POST">
    <button value="delete" name="btn" onclick="if(window.confirm('Delete user?\nWARNING! THIS IS ACTION CANNOT BE UNDONE!'))
{document.frm.submit();}else{return false;}">
    Delete
    </button>
</form>

当您return false;时,表单将无法提交,因此点击Cancel会使表单无法提交,而点击Ok则会提交

演示:http://jsfiddle.net/qXJWL/

答案 1 :(得分:1)

尝试else { return false; }

<form name="frm" action="users.jsp/manage-users?status=delete&index=1" method="POST">
    <button value="delete" name="btn" onclick="if(window.confirm('Delete user?\nWARNING! THIS IS ACTION CANNOT BE UNDONE!'))
{document.frm.submit();} else { return false; }">Delete</button>
</form>

答案 2 :(得分:1)

为了更好的做法,请将脚本与html分开,在按取消时使用return false并使用return formSubmit(),例如

<强> JAVASCRIPT

function formSubmit(){
    if(window.confirm('Delete user?\nWARNING! THIS IS ACTION CANNOT BE UNDONE!')){
        document.frm.submit();
    }else{
        return false;
    }
}

<强> HTML

<form name="frm" action="users.jsp/manage-users?status=delete&index=1" method="POST">
    <button value="delete" name="btn" onclick="return formSubmit()" id="myButton">
    Delete
    </button>
</form>

DEMO