如何解决模态框内取消按钮触发表单提交的问题
解决模态框Close按钮触发表单提交的问题
以下是几个简单直接的解决方案:
方案1:修改Close按钮的type属性
form里的button默认类型是submit,点击会触发表单提交。只需给Close按钮加上type="button"属性,就能让它只执行关闭模态框的逻辑,不会触发表单提交:
<button id="closeModalBtn" type="button" class="px-4 py-2 bg-red-600 text-white rounded-md">Close</button>
方案2:用JavaScript阻止默认提交行为
如果不想修改按钮类型,可以给Close按钮添加点击事件,阻止表单的默认提交动作,同时关闭模态框:
<button id="closeModalBtn" class="px-4 py-2 bg-red-600 text-white rounded-md" onclick="event.preventDefault(); document.getElementById('modalBackdrop').classList.add('hidden');">Close</button>
或者用单独的JS代码监听事件:
document.getElementById('closeModalBtn').addEventListener('click', function(e) { e.preventDefault(); // 阻止表单提交 document.getElementById('modalBackdrop').classList.add('hidden'); // 关闭模态框 });
方案3:将Close按钮移出form标签
把Close按钮放到form外面的模态框底部区域,这样它就不属于表单的一部分,自然不会触发表单提交:
<div class="bg-white rounded-lg overflow-hidden shadow-lg max-w-md w-full dark:bg-gray-800"> <div class="p-4 border-b dark:border-gray-700"> <h2 class="text-xl font-semibold text-gray-800 dark:text-gray-200">New Folder</h2> </div> <form action="{{ route('folder.create') }}" enctype="multipart/form-data" method="POST"> @csrf <div class="flex items-center justify-center w-full"> <input type="text" id="default-input" name="folder_name" class="mr-2 ml-2 bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"> </div> <div class="p-4 border-t dark:border-gray-700"> <button type="submit" class="px-4 py-2 bg-green-600 text-white rounded-md mr-2">Submit</button> </div> </form> <div class="p-4 flex justify-end"> <button id="closeModalBtn" class="px-4 py-2 bg-red-600 text-white rounded-md">Close</button> </div> </div>
内容的提问来源于stack exchange,提问作者Ductn
相关产品推荐
相关产品推荐

