set city with cookies in wordpress

In a WordPress listing website, I have a search form in the header of all of the pages. I want to use cookies to save the value selected in the city field of this form for future visits to the site, so that the city field of this form will be entered in the same city that I have selected before.

I am not a professional and please provide me with the desired information in full along with the necessary explanations.
Thank you

I found this code and used this in function.php:


function add_city_selection_script() {
    ?>
    <script type="text/javascript">
        document.addEventListener('DOMContentLoaded', function () {
            const locationField = document.querySelector('.field-address');
            
            // A function to read the cookie value
            function getCookie(name) {
                const value = `; ${document.cookie}`;
                const parts = value.split(`; ${name}=`);
                if (parts.length === 2) return parts.pop().split(';').shift();
            }

            // Set the value of the city field from the cookie
            const selectedCity = getCookie('selected_city');
            if (selectedCity && locationField) {
                locationField.value = decodeURIComponent(selectedCity);
            }

            if (locationField) {
                locationField.addEventListener('change', function () {
                    const selectedCity = locationField.value;
                    document.cookie = "selected_city=" + encodeURIComponent(selectedCity) + "; path=/; max-age=" + (60 * 60 * 24 * 30); // 30 days
                });
            }
        });
    </script>
    <?php
}
add_action('wp_footer', 'add_city_selection_script');



function get_selected_city_from_cookie() {
    if (isset($_COOKIE['selected_city'])) {
        return urldecode($_COOKIE['selected_city']);
    }
    return null;
}

add_action('wp_footer', 'display_selected_city');
function display_selected_city() {
    $selected_city = get_selected_city_from_cookie();
    if ($selected_city) {
        echo '<div>Selected city: ' . esc_html($selected_city) . '</div>';
    }
}


But I failed to reach the desired goal.