Javascript-форум (https://javascript.ru/forum/)
-   Events/DOM/Window (https://javascript.ru/forum/events/)
-   -   отправить данные из div, в котором нажата кнопка (https://javascript.ru/forum/events/81354-otpravit-dannye-iz-div-v-kotorom-nazhata-knopka.html)

Don_Conteo 13.11.2020 05:50

отправить данные из div, в котором нажата кнопка
 
Прошу помощи знатоков. Есть несколько div с одинаковыми кнопками (значения для полей в дивах берутся из базы с помощью ТЛ) и модальное окно (одно для всех кнопок). Необходимо при нажатии на любую из этих кнопок открыть модальное окно и его в скрытый input (calor) добавить значение (количество ккал elem.calories) именно из того div, в котором была нажата кнопка.

кусок HTML (здесь привел три блока для примера, на самом деле их, конечно же, в разы больше):

<div class="foodN">
                        <img th:src="@{__${#httpServletRequest.scheme + '://' + #httpServletRequest.serverName + ':' + #httpServletRequest.serverPort}__/images/peanut.jpg}">
                        <p th:each="elem : ${food[0]}" th:text="${elem.name}"></p>
                        <a>Ккал на 100 грамм:</a>
                        <strong><a th:each="elem : ${food[0]}" th:text="${elem.calories}"></a></strong>
                        <input type="button" id="0" value="+" class="add">
                    </div>

                    <div class="foodN">
                        <img th:src="@{__${#httpServletRequest.scheme + '://' + #httpServletRequest.serverName + ':' + #httpServletRequest.serverPort}__/images/brasilNut.jpg}">
                        <p th:each="elem : ${food[1]}" th:text="${elem.name}"></p>
                        <a>Ккал на 100 грамм:</a>
                        <strong><a th:each="elem : ${food[1]}" th:text="${elem.calories}"></a></strong>
                        <input type="button" value="+" class="add">
                    </div>

                    <div class="foodN">
                        <img th:src="@{__${#httpServletRequest.scheme + '://' + #httpServletRequest.serverName + ':' + #httpServletRequest.serverPort}__/images/mindal.jpg}">
                        <p th:each="elem : ${food[2]}" th:text="${elem.name}"></p>
                        <a>Ккал на 100 грамм:</a>
                        <strong><a th:each="elem : ${food[2]}" th:text="${elem.calories}"></a></strong>
                        <input type="button" value="+" class="add">
                    </div>


модальное окно

<div class="overlay" id="modal-background">
        <div class="flex-popup" id = flex>
            <div class="popup" id="popup">
                <input type="hidden" name="calor" id="calor">
                <input class="input" placeholder="Введите количество в граммах" id="quantity" type="text" width="50px" background-color="white">
                <button id="addToRes" class="addBtn" title="Добавить">Добавить</button>
                <button id="butClose" class="closeBtn" title="Отмена">Закрыть</button>
            </div>
        </div>
    </div>


JS

<script>
        $(function() {
            $(".add").click(function () {
                document.getElementById("modal-background").style.display = "block";
                });

            $("#butClose").click(function () {
                document.getElementById("modal-background").style.display = "none";
                });

            $(document).mouseup(function (e){
                var modalctr = $("#modal-background");
                var modal = $(".popup");
                if (!modal.is(e.target) && modal.has(e.target).length === 0){
                modalctr.hide();
                }
            });
        });

        let nuts = document.getElementById('nutsPage'),
            mushrooms = document.getElementById('mushroomsPage')

        nuts.addEventListener( 'click', function( e ) {
            document.getElementById("foodMushrooms").style.display = "none";
            document.getElementById("foodNuts").style.display = "block";
        });

        mushrooms.addEventListener( 'click', function( e ) {
            document.getElementById("foodNuts").style.display = "none";
            document.getElementById("foodMushrooms").style.display = "block";
        });
    </script>

voraa 13.11.2020 07:06

$(".add").click(function () {
      document.getElementById("modal-background").style.display = "block";
     let block = this.closest('.foodN')  // блок в котором щелкнули
     ....
});

Don_Conteo 14.11.2020 00:01

Спасибо большое, но я все равно пока не понимаю, каким именно образом мне из этого конкретного div'а выдернуть значение из <а>, которое берется там из базы.

voraa 14.11.2020 15:26

У <a> нет значения. Есть текст ссылки. Есть атрибут href. Что вам надо?
получить <a> из вашего <div>
let a = block.querySelector('a')


Часовой пояс GMT +3, время: 02:29.