简体   繁体   中英

Javascript form submits but not with all appended form fields

I have a Google places auto completion search bar. The post data from the form is read in Symfony. The search bar works fine but the user has to click on a place in the list, so I made it that if the user hits enter it'd simulate a down arrow and select the first suggestion.

If a user clicks on a place in the list I do a jQuery form.append to add the lat/lng If a user hits enter I can see the form.append happening in inspect elements but the fields are not showing up in the post data.

Below is the code that handles the auto completion and simulated down arrow

window.autocomplete = null;
    const form = $('#search-form');

    function initAutocomplete() {
        var pac_input = document.getElementById('search-input');

        (function pacSelectFirst(input) {
            // store the original event binding function
            var _addEventListener = (input.addEventListener) ? input.addEventListener : input.attachEvent;

            function addEventListenerWrapper(type, listener) {
                // Simulate a 'down arrow' keypress on hitting 'return' when no pac suggestion is selected,
                // and then trigger the original listener.
                if (type === "keydown") {
                    var orig_listener = listener;
                    listener = function (event) {
                        var suggestion_selected = $(".pac-item-selected").length > 0;
                        if (event.which === 13 && !suggestion_selected) {
                            var simulated_downarrow = $.Event("keydown", {
                                keyCode: 40,
                                which: 40
                            });
                            orig_listener.apply(input, [simulated_downarrow]);
                        }
                        orig_listener.apply(input, [event]);
                    };
                }
                _addEventListener.apply(input, [type, listener]);
            }

            input.addEventListener = addEventListenerWrapper;
            input.attachEvent = addEventListenerWrapper;

            // Create the autocomplete object, restricting the search to geographical location types.
            autocomplete = new google.maps.places.Autocomplete(input,
                {types: ['geocode']});

            autocomplete.addListener('place_changed', fillInAddress);

        })(pac_input);
    }

Below is the function fillInAddress which adds the fields.

function fillInAddress() {
        let place = autocomplete.getPlace();
        console.log(place)
        let lat = place.geometry.location.lat();
        let lng = place.geometry.location.lng();
        let searchplace = place.formatted_address;
        let searchplaceElement = $('#searchplace');
        if (!searchplaceElement.length) {
            form.append("<input id='searchplace' name='searchplace' type='hidden' value='" + searchplace + "'>")
            form.append("<input id='lat' name='lat' type='hidden' value='" + lat + "'>")
            form.append("<input id='lng' name='lng' type='hidden' value='" + lng + "'>")
        } else {
            searchplaceElement.val(searchplace);
            $('#lat').val(lat);
            $('#lng').val(lng);
        }
}

Below is the HTML form part.

        <form action="/restaurants" id="search-form" method="post">
            <div class="input-group input-group-lg">
                <div class="input-group-prepend">
                    <span class="input-group-text"><i class="fa fa-map-marker"></i></span>
                </div>
                <input id="search-input" class="form-control shadow-none" type="text" placeholder="Zoeken op adres of postcode">
                <div class="input-group-append">
                    <button type="submit" class="btn btn-dark">Zoeken</button>
                </div>
            </div>
        </form>

I have to add I'm not a real good export on jQuery or Javascript.

The standard submit button only submits form fields that were initially loaded. Fields that were added after DOM loads, have to get submitted manually for example like this:

$('#search-form).on('submit', function(e) {
    e.preventDefault();
    $.post($(this).attr('action'), $(this).serialize());
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM