溫馨提示×

ShowModalDialog在表單提交中的應(yīng)用

小樊
81
2024-10-16 13:33:13
欄目: 編程語言

ShowModalDialog 是一個 JavaScript 函數(shù),用于顯示一個模態(tài)對話框(modal dialog),通常用于向用戶請求信息或確認操作。在表單提交過程中,可以使用 ShowModalDialog 來實現(xiàn)一些交互式的操作,例如確認刪除操作、提示輸入額外的信息等。

以下是一個簡單的示例,展示了如何在表單提交中使用 ShowModalDialog

  1. 創(chuàng)建一個 HTML 表單:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form with ShowModalDialog</title>
</head>
<body>
    <form id="myForm">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>
        <br><br>
        <button type="submit">Submit</button>
    </form>

    <script src="script.js"></script>
</body>
</html>
  1. 創(chuàng)建一個 JavaScript 文件 script.js,并在其中編寫以下代碼:
document.getElementById('myForm').addEventListener('submit', function (event) {
    event.preventDefault(); // 阻止表單默認提交行為

    // 顯示模態(tài)對話框
    showModalDialog();
});

function showModalDialog() {
    const dialog = document.createElement('div');
    dialog.style.position = 'fixed';
    dialog.style.top = '0';
    dialog.style.left = '0';
    dialog.style.width = '100%';
    dialog.style.height = '100%';
    dialog.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
    dialog.style.display = 'flex';
    dialog.style.justifyContent = 'center';
    dialog.style.alignItems = 'center';

    const content = document.createElement('div');
    content.style.backgroundColor = 'white';
    content.style.padding = '20px';
    content.style.borderRadius = '5px';
    content.style.width = '300px';

    const message = document.createElement('p');
    message.style.margin = '0';
    message.textContent = 'Are you sure you want to submit the form?';

    const confirmButton = document.createElement('button');
    confirmButton.style.marginRight = '10px';
    confirmButton.textContent = 'Yes';
    confirmButton.onclick = function () {
        submitForm();
        closeDialog();
    };

    const cancelButton = document.createElement('button');
    cancelButton.textContent = 'No';
    cancelButton.onclick = function () {
        closeDialog();
    };

    content.appendChild(message);
    content.appendChild(confirmButton);
    content.appendChild(cancelButton);

    dialog.appendChild(content);
    document.body.appendChild(dialog);

    function closeDialog() {
        document.body.removeChild(dialog);
    }
}

function submitForm() {
    // 在這里執(zhí)行表單提交操作,例如發(fā)送 AJAX 請求
    console.log('Form submitted!');
}

在這個示例中,當(dāng)用戶點擊提交按鈕時,會顯示一個模態(tài)對話框,詢問用戶是否確實要提交表單。用戶可以選擇“Yes”或“No”,對應(yīng)的操作會執(zhí)行相應(yīng)的邏輯。

0