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.
Some early September spring shots from a bushwalk, It is still too early for wildflowers.
I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…
If you ever needed a simple solution in Laravel to delete an entire directory and…
How to enforce only one user to register or be registered in a Laravel web…