I'm trying to make all the select elements for my products interactive in my Amazon clone project. I know I should use `querySelectorAll` to select all the `` tags, but I'm unclear about how to loop through them and get their values. Changing the original array to include select elements for each product doesn't seem efficient to me. Is there a way to achieve this simply with `querySelectorAll`?
2 Answers
Congrats on creating your Amazon clone! That sounds really exciting. Just a tip: to keep it simple with all your selects, grab them using `querySelectorAll` and loop through each element to add an event listener for changes. Here’s a basic implementation you could try:
```javascript
document.querySelectorAll('.js-select').forEach((select, index) => {
select.addEventListener('change', () => {
const newQty = parseInt(select.value);
console.log(`Product ${index} quantity changed to`, newQty);
});
});
```
This will keep everything in sync without complicating your product array.
You can definitely handle all the form values using the `FormData` API! Just wrap all your input fields and selects in a `` tag, and then you can create a `FormData` instance from that form. This way, when you submit the form, it’ll capture all values nicely. Here’s a quick example:
```javascript
document.getElementById('myForm').addEventListener('submit', function (e) {
e.preventDefault();
const formData = new FormData(this);
console.log(Object.fromEntries(formData));
});
```
This outputs your form data as an object, and you can even iterate through the entries if needed!
Isn’t this just for one product? I have multiple products, so won't the same form ID mess things up?
Using `var` is a bit outdated. You should definitely consider using `const` or `let` instead. Just a thought!