I have four divs and each contains a title, image and button. How can i make the click of that button pick the details of the div it resides in only. I plan to do this with just one function for all four divs because i will be creating more divs on the page.
I have created the divs and all shares the same ids. Each div has its own title, image and button. After creating the function and using the onclick event listener, the function always returns the value of the first div even if i click the second, third or fourth.
I am new to JS but not afraid to grow and master it. I need help on this. Thanks
const forms = document.querySelectorAll("button[type=submit]");
for (const form of forms) {
form.addEventListener('click', function(event) {
let productName = document.getElementById('productName').innerText;
let productImg = document.getElementById('productImg').src;
let package = document.getElementById('package').value;
alert('Working See Details Below:' + '\n' + productName + '\n\n' + productImg + '\n\n' + package);
})
}
form {
width: 25%;
height: inherit;
overflow: auto;
float: left;
}
<body>
<form id="form">
<h1 id="productName">Div 1</h1>
<img src="img\red.jpg" alt="Trial Image" width="10%" height="100%" class="images" id="productImg"><br>
<select name="category" id="package">
<option value="Business Plan">Business Plan</option>
<option value="Feasibility Report">Feasibility Report</option>
</select>
<button type="submit">Try it</button>
</form>
<form id="form">
<h1 id="productName">Div 2</h1>
<img src="img\yellow.jpg" alt="Trial Image" width="10%" height="100%" class="images" id="productImg"><br>
<select name="category" id="package">
<option value="Business Plan">Business Plan</option>
<option value="Feasibility Report">Feasibility Report</option>
</select>
<button type="submit">Try it</button>
</form>
<form id="form">
<h1 id="productName">Div 3</h1>
<img src="img\blue.jpg" alt="Trial Image" width="10%" height="100%" class="images" id="productImg"><br>
<select name="category" id="package">
<option value="Business Plan">Business Plan</option>
<option value="Feasibility Report">Feasibility Report</option>
</select>
<button type="submit">Try it</button>
</form>
<form id="form">
<h1 class="productName">Div 4</h1>
<img src="img\black.jpg" alt="Trial Image" width="10%" height="100%" class="images" id="productImg"><br>
<select name="category" id="package">
<option value="Business Plan">Business Plan</option>
<option value="Feasibility Report">Feasibility Report</option>
</select>
<button type="submit">Try it</button>
</form>
My expectations as explained earlier is to have the button of a div return the details of the title, image source and user input from the select option moved to localStorage when i can then use it on other pages on the app.