表单始终使用Javascript提交确认

时间:2019-05-28 22:05:50

标签: javascript php sql

该表单已经工作了一段时间,但是我移动了一些代码并且无法还原(一个经验教训),现在该代码无法正常运行。简而言之,用户单击删除按钮>删除按钮将特定的条目ID发送给函数,函数获取表单ID,“确认删除”,然后应发送到我的delete_entry.php代码。现在,即使我单击“否”,表单也始终会提交,并且添加了警报以告诉我它走的路。

我尝试注释掉表单,但它仍然提交,因此我认为它没有明确地与确认函数联系在一起(尽管可能很疯狂)

if ($entry['SubEntryID'] == "0") { ?>
<div id="post"><!-- This is the main post-->
    <div id="main">
        <div id="title">
            <?php echo $entry['EntryID']; ?>
            <?php echo $entry['Title']; ?>
        </div><br />
        <p><?php echo $entry['Body']; ?></p><br />
        <div id="postinfo">
          At: <?php echo $entry['CreateDate']; ?><br/>
          Posted by - <?php echo $entry['UserName']; ?>
        </div>
<!-- Start the form for the delete button -->
<form action="Delete_entry.php" method="post" id="Delete<?php echo $entry['EntryID'];?>">    
<input type="hidden" readonly="true" name="EntryID" value="<?php echo $entry['EntryID']; ?>" />
<input type="hidden" readonly="true" name="UserID" value="<?php echo $entry['UserID']; ?>" />
<?php if ($userid == 1 || $userid == $entry['UserID']) { ?>
    <input onclick="confirmdelete('Delete<?php echo $entry['EntryID'];?>')" type="image" src="redx.png" alt="Delete Post" id="btnDelete" value="Delete Post"/>
<?php } ?><br />
        </form>
</div>
function confirmdelete(eid) {

    var retval = confirm("Are you sure you want to delete?" + eid + "?");

    if (retval == true) {
        alert("You said Yes");
        document.getElementById(eid).submit();
        }
    else
    {
        alert("You said No");
    }
}

我希望删除按钮调用该函数,该函数通过以下方式进行响应:如果为真,则提交表单,如果为假,则取消表单提交。表单页面仅在确认为true时才被调用,然后submit()

1 个答案:

答案 0 :(得分:1)

首先,confirmdelete()不会返回任何true / false,因此没有代码阻止表单提交。其次,即使函数返回false,表单也仍然会提交,因为您有2个提交(表单和onclick)。

将函数调用移至表单的onsubmit()。删除onclick,因为默认情况下输入类型的图像提交表单。这是代码:

表格:

<form action="Delete_entry.php" method="post" 
   id="Delete<?php echo $entry['EntryID'];?>" 
   onsubmit="return confirmdelete(<?php echo $entry['EntryID'];?>)"> 

然后单击按钮(单击已删除):

<input type="image" src="redx.png" alt="Delete Post" id="btnDelete" value="Delete Post" />

最后是JavaScript(返回true / false):

function confirmdelete(eid) {

    if (confirm("Are you sure you want to delete?" + eid + "?")) {
        alert("You said Yes");
        return true;
    }
    else
    {
        alert("You said No");
        return false;
    }
}