Form substitution from DOM , element with id

13 Views Asked by At

Form substitution from DOM , element with id

A brief description of the task and the problem encountered.

Task. Services network page. When you click on the button (order a service), a modal window (application form) opens: The task is to receive a letter with an application for the service and find out which of the 4 buttons on the page was pressed (that is, the selected service)

Solution. 1) Each service card is a div (consisting of img, p, button). 2) There is a hidden field in the form, I thought why not manually assign the button id (Example in the attached image: cold glazing), and assign the same class to all 4 buttons. 3) Write a script in which the function finds the id of the specifically pressed button and substitutes it based on the class in the hidden form field.

I wrote the following script, placed it in footer.php, since it will not work in the header, because there is nothing to show, the page has not yet loaded:

Problem!! It doesn't matter which of the four buttons I press, I get the id first. Accordingly, I can’t understand why he substitutes the value from the first dom element for me if the id is individual. Somewhere in my code I have a jamb. Guys who can correct in the code what I did wrong.

<script lang="javascript">
    (function () {
        const buttonClassName = 'shop';
        const ids = ['field_4b68799'];

        for (const buttn of document.getElementsByClassName('shop')) {
            buttn.addEventListener("click", setTextForEmail);
        }

        const findForm = () => new Promise(resolve => {
            const intrv = setInterval(() => {
                ids.forEach(id => {
                    const fullId = 'form-field-' + id;
                    if (document.getElementById(fullId) != null) {
                        clearInterval(intrv);
                        resolve();
                    }
                });
            }, 100);
        });

        function setTextForEmail() {
            findForm().then(() => {
                ids.forEach(id => {
                    const fullId = 'form-field-' + id;
                    document.getElementById(fullId).value = document.getElementsByClassName(buttonClassName)[0].getElementsByTagName('a')[0].getAttribute('text');
                });
            });
        }
    })();
</script>
0

There are 0 best solutions below