Using jQuery to select text and input values based on closest parameters.
closest() will get the first element matching by traversing up, whilst find() will descend until the match is found.
This method is similar to get an input value, but instead you want to only go as high as the current row. Then get the input’s value with val() on the id of the input.
The jQuery:
$(document).ready(function () { $(".buy-btn").click(function () { let item = $(this).closest('.card').find('.item-text').text(); let size_text = $(this).closest('.row').find('.size-text').text(); let size = $(this).closest('.row').find('#size').val(); let price = $(this).closest('.row').find('#price').val(); alert(item + ' ' + size_text + ' ' + size + ' ' + price); }); });
The HTML:
<div class="container"> <div class="card"> <div class="card-header"> <h1 class="item-text">Cashews</h1> </div> <div class="card-body"> <form> <div class="row"> <h4 class="size-text mt-2">Small</h4> <div class="col-4"> <label for="size">Size</label> <input type="text" class="form-control" id="size" placeholder="" value="250 Grams" disabled> </div> <div class="col-4"> <label for="price">Price $</label> <input type="number" class="form-control" id="price" placeholder="" value="2.00" disabled> </div> <div class="col-4 mt-4"> <button type="button" class="btn btn-success btn-sm buy-btn">Buy</button> </div> </div> <div class="row"> <h4 class="size-text mt-2">Medium</h4> <div class="col-4"> <label for="size">Size</label> <input type="text" class="form-control" id="size" placeholder="" value="500 Grams" disabled> </div> <div class="col-4"> <label for="price">Price $</label> <input type="number" class="form-control" id="price" placeholder="" value="4.00" disabled> </div> <div class="col-4 mt-4"> <button type="button" class="btn btn-success btn-sm buy-btn">Buy</button> </div> </div> <div class="row"> <h4 class="size-text mt-2">Large</h4> <div class="col-4"> <label for="size">Size</label> <input type="text" class="form-control" id="size" placeholder="" value="1 Kilogram" disabled> </div> <div class="col-4"> <label for="price">Price $</label> <input type="number" class="form-control" id="price" placeholder="" value="7.00" disabled> </div> <div class="col-4 mt-4"> <button type="button" class="btn btn-success btn-sm buy-btn">Buy</button> </div> </div> </form> </div> </div> </div>
A drained and empty Kennington reservoir images from a drone in early July 2024. The…
Merrimu Reservoir from drone. Click images to view larger.
Using FTP and PHP to get an array of file details such as size and…
Creating and using Laravel form requests to create cleaner code, separation and reusability for your…
Improving the default Laravel login and register views in such a simple manner but making…
Laravel validation for checking if a field value exists in the database. The validation rule…