ウェブサイト検索

javascript - 削除する前に確認メッセージを表示する方法は?


削除をクリックしたときに確認メッセージを表示したいです(これはボタンまたは画像のどちらかかもしれません)。ユーザーが'OK'を選択した場合は削除が行われ、'キャンセル'をクリックした場合は何も起こりません。

ボタンがクリックされたときにこれをechoしようとしましたが、echoすると入力ボックスやテキストボックスのスタイルやデザインが失われてしまいます。

回答 #1

このコードをボタンのonclickイベントに書いてください:

var result = confirm("Want to delete?");
if (result) {
    //Logic to delete the item
}

回答 #2

次のようによりよく使うことができます

 <a href="url_to_delete" onclick="return confirm('Are you sure you want to delete this item?');">Delete</a>

回答 #3

これは、目立たないJavaScriptを使い、確認メッセージをHTML内に保持する方法です。

<a href="/delete" class="delete" data-confirm="Are you sure to delete this item?">Delete</a>

これは純粋なバニラJSで、IE 9以上に対応しています:

var deleteLinks = document.querySelectorAll('.delete');

for (var i = 0; i < deleteLinks.length; i++) {
  deleteLinks[i].addEventListener('click', function(event) {
      event.preventDefault();

      var choice = confirm(this.getAttribute('data-confirm'));

      if (choice) {
        window.location.href = this.getAttribute('href');
      }
  });
}

実際の動作を見る: http://codepen.io/anon/pen/NqdKZq

回答 #4

function ConfirmDelete()
{
  return confirm("Are you sure you want to delete?");
}


<input type="button" onclick="ConfirmDelete()">

回答 #5

それは非常に簡単で、一行のコードです

<a href="#" title="delete" class="delete" onclick="return confirm('Are you sure you want to delete this item')">Delete</a>

回答 #6

これを試してみて。私にはうまくいきます

 <a href="delete_methode_link" onclick="return confirm('Are you sure you want to Remove?');">Remove</a>

回答 #7

user1697128 を改良する(まだコメントできないので)

<script>
    function ConfirmDelete()
    {
      return confirm("Are you sure you want to delete?");
    }
</script>    
    
<button Onclick="return ConfirmDelete();" type="submit" name="actiondelete" value="1"><img src="images/action_delete.png" alt="Delete"></button>

キャンセルが押された場合、フォームの送信をキャンセルします

回答 #8

私がこれを行う方法を提案したいと思います:

<form action="/route" method="POST">
<input type="hidden" name="_method" value="DELETE"> 
<input type="hidden" name="_token" value="the_token">
<button type="submit" class="btn btn-link" onclick="if (!confirm('Are you sure?')) { return false }"><span>Delete</span></button>
</form>

関連記事