无法在我的表单按钮上实现Confirm()函数

时间:2018-12-13 12:42:24

标签: javascript jquery html

我正在尝试将Confirm()函数添加到位于用于更新图像信息的页面上的2个按钮上。第一个按钮保存有关图像的已更改信息,第二个按钮删除图像。这两个按钮都在POST表单中。不幸的是,我面临着两个问题。

首先,即使当我单击保存信息的按钮时弹出确认框,在我单击确认框内的“确定”或“取消”并保存信息之前,表单也会发送POST请求。 / p>

其次,我相信“删除”按钮也可以做同样的事情。弹出询问我是否要删除的框,即使我不单击任何内容,该图像也会从数据库中删除。另外,如果我单击“取消”,效果是相同的,图像也会从数据库中删除。

最后,为什么它说在$(document).ready(function(){})内时,confirmFunction()未定义。但是当它在外面时工作正常吗?

任何有关为什么会发生这种情况的提示都将不胜感激。

使用编辑按钮的第一个表单。

<form action="{{ route('updateArtwork', $image) }}" method="POST" enctype="multipart/form-data">
    <div class="form-group">
        <label class='label' for="artwork-tags">Tags</label>
        <input class='input' type="text" name="artwork-tags" placeholder="Tags" value='{{ $tagString }}'>
    </div>

    <button onclick='confirmFunction()' class='green-btn' type="submit" name="submit">Save</button>
</form>

使用删除按钮的第二种形式。

<form method="POST" action="{{route('DeleteArtwork', $image->id)}}">
    <button onclick='confirmFunction()' class='red-btn' type="submit">Delete Image</button>
</form>

JavaScript。

$(document).ready(function() {

});

function confirmFunction() {
    confirm("Are you sure?");
}

1 个答案:

答案 0 :(得分:1)

  1. 使用JavaScript获取表单(我在示例中使用id
  2. 添加提交事件侦听器(在提交表单时触发)
  3. 做您想做的事情

function confirmFunction(event) {
  const okToContinue = confirm("Are you sure?");
  if (okToContinue === false) {
    event.preventDefault();
  }
}

document.getElementById('form').addEventListener('submit', (event) => {
  confirmFunction(event);
});
<form id="form" method="GET" enctype="multipart/form-data">
  <div class="form-group">
    <label>Label</label>
    <input type="text" name="value" placeholder="value" value='value'>
  </div>

  <button type="submit" name="submit">Save</button>
</form>