在页面开始 HTML 上将焦点设置在输入框上

问题描述 投票:0回答:1

我的 html 页面有问题。我想在页面加载时将焦点设置在第一个输入框上,但我的所有尝试都以失败告终。我不确定我做错了什么,因为我不是前端开发人员。有人愿意发送提示出了什么问题吗?

<!DOCTYPE html>
<html>
<head>
    <title>Product Input</title>
    <style>
        /* Modal styles */
        .modal {
            display: none; /* Hidden by default */
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 400px;
            max-width: 90%;
            padding: 20px;
            background-color: white;
            border-radius: 5px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
        }

        .modal-content {
            margin-top: 20px;
        }

        /* Center all other elements */
        body, h1, form, input, ul {
            text-align: center;
        }

        ul {
            list-style: none;
            padding: 0;
        }

        input[type="submit"],
        button {
            padding: 10px 20px;
            font-size: 18px;
            margin-top: 10px;
        }

        /* Additional styling for different screen resolutions */
        @media (max-width: 480px) {
            body {
                font-size: 16px;
            }
        }

        @media (min-width: 481px) and (max-width: 1350px) {
            body {
                font-size: 20px;
            }
        }

        @media (min-width: 1351px) {
            body {
                font-size: 24px;
            }
        }
        .logout-button {
            position: absolute;
            top: 10px;
            right: 10px;
        }
    </style>
</head>
<body>
    <h1>Product Input</h1>
    <form method="POST" action="/">
        <label for="user_input_1">Enter First Input:</label>
        <br>
        <input type="text" id="user_input_1" name="user_input_1" required>
        <br>
        <input type="submit" value="Submit">
    </form>
    <p style="color: red;">{{ error }}</p>
    <!-- Logout button -->
    {% if 'username' in session %}
        <a class="logout-button" href="{{ url_for('logout') }}">Logout</a>
    {% endif %}
    
    <h2>Added Inputs:</h2>
    <ul>
        {% for item in user_inputs %}
            <li>{{ item[0] }} - {{ session.get('product_name', '') }} - {{ session.get('product_code', '') }} - {{ item[1] }}</li>
        {% endfor %}
    </ul>
    
    <form method="POST" action="/unique">
        <button type="submit">Unique</button>
    </form>

    {% if show_second_input %}
    <!-- The Modal -->
    <div class="modal" id="second-input-modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal()">&times;</span>
            <h1>Enter Second Input</h1>
            <form id="second-input-form" onsubmit="handleSubmit(event)">
                <input type="text" id="user_input_2" name="user_input_2" required>
                <br>
                <input type="submit" value="Submit">
            </form>
            <p id="error-message-modal" style="color: red;"></p>
        </div>
    </div>
<!-- Script to handle the modal -->
<script>
    // Set focus on the first input box when the page loads
    document.addEventListener('DOMContentLoaded', function () {
        document.getElementById('user_input_1').focus();
        // Check if the second input modal should be shown on page load
        showModal();
    });

    // Function to show the modal and set focus on the second input box
    function showModal() {
        const modal = document.getElementById("second-input-modal");
        modal.style.display = "block";
        document.getElementById('user_input_2').focus();
    }

    // Function to close the modal and set focus on the first input box
    function closeModal() {
        const modal = document.getElementById("second-input-modal");
        modal.style.display = "none";
        document.getElementById('user_input_1').focus();
    }

 // Function to reset focus on the first input box after successful form submission
 function resetFocusOnFirstInput() {
    closeModal(); // Close the modal
    document.getElementById('user_input_1').focus(); // Set focus on the first input box
}

function handleSubmit(event) {
    event.preventDefault(); // Prevent the form from submitting normally

    const user_input_2 = document.getElementById("user_input_2").value;
    const formData = new FormData(); // Create a new FormData object
    formData.append('user_input_2', user_input_2); // Add the user_input_2 field to the form data

    fetch("/check_second_input", {
        method: "POST",
        body: formData, // Use the formData object as the request body
    })
    .then((response) => response.json())
    .then((data) => {
        if (data.error) {
            document.getElementById("error-message-modal").innerText = data.error;
            // Close the modal in case of an invalid input
            closeModal();
        } else {
            if (!data.already_added) {
                // If the input is valid and not already added, reset focus on the first input box
                resetFocusOnFirstInput();
                // Refresh the list of added inputs
                updateAddedInputsList();
            } else {
                // If the input is valid but already added, show the error message without closing the modal
                document.getElementById("error-message-modal").innerText = data.error;
            }
        }
    });
}

// Function to update the list of added inputs dynamically
function updateAddedInputsList() {
    // Fetch the updated page content from the server using the same endpoint that renders the index.html template
    fetch("/", {
        method: "GET",
    })
    .then((response) => response.text())
    .then((html) => {
        // Create a temporary div element to extract the list content from the fetched HTML
        const tempDiv = document.createElement("div");
        tempDiv.innerHTML = html;

        // Find the list container element and replace the current list content with the updated content
        const listContainer = document.querySelector("ul");
        listContainer.innerHTML = tempDiv.querySelector("ul").innerHTML;
    });
}
</script>

{% endif %}
</body>
</html>

我尝试使用 document.getElementById('user_input_1').focus() 函数,但它专注于第一个输入框,只有当输入错误的输入时,焦点才会被正确设置。

javascript html focus
1个回答
0
投票

您的问题与页面加载时处理焦点的方式有关。您的代码尝试将焦点集中在第一个输入 user_input_1 上,但此后立即调用 showModal() 函数,该函数将焦点设置在模式内的第二个输入 user_input_2 上。

要解决此问题,您应该根据当前是否需要有条件地显示模式。如果未显示模式,焦点仍位于第一个输入上。

这里有一个快速解决方法:

document.addEventListener('DOMContentLoaded', function () {
    // Only show the modal if it's necessary
    if (/* condition to show the modal */) {
        showModal();
    } else {
        document.getElementById('user_input_1').focus();
    }
});

将 /* 条件显示模态 */ 替换为决定何时显示模态的任何条件。如果未显示模式,第一个输入将按预期聚焦。

请注意,页面加载时,您当前的代码结构将始终显示模式。相应地调整条件以控制模态出现的时间。

© www.soinside.com 2019 - 2024. All rights reserved.