I have a low level knowledge of javascript and am trying to create a basic image based quiz that passes data back to a search page for local businesses.
Each image would have it’s own “tag” as the image ID that relates to one of the options in the search. Ie. Outdoor, Ballroom, Barn, Garden, etc.
Upon submission, it would send the selected image ID’s data to www.sitename/search/?_characteristics=TAG1,TAG2,TAG3
That search page will filter the business listings by the tags. Currently it’s search function filters the businesses with the following format: website.com/search/?_characteristics=TAG1%2CTAG2
The HTML would look like this:
<img src="http://website.com/image1" id="TAG1"/> <br/> <img src="http://website.com/image2" id="TAG2"/> <form action="https://website.com/business/?&_characteristics=TAG1, TAG2, TAG3" method="get"> <input type="submit" value="View Selected"/>
Advertisement
Answer
What you want is the following
- Register a click handler on your images to
- Capture ids into a collection (array or Set)
- Toggle the “selected” class
- Register a submit handler on the form to inject an hidden input element, transforming the tag collection into a CSV and setting it to the input value
const form = document.querySelector("form") const tags = new Set() document.querySelectorAll("img[id]").forEach(img => { img.addEventListener("click", () => { const selected = img.classList.toggle("selected") tags[selected ? "add" : "delete"](img.id) }) }) form.addEventListener("submit", (e) => { const input = Object.assign(document.createElement("input"), { name: "_characteristics", type: "hidden", value: ([...tags]).join(",") }) form.append(input) // this is just for the example, omit the following e.preventDefault() console.log(`Submitting to ${form.action}?${new URLSearchParams(new FormData(form))}`) input.remove() })
img { border: 2px solid grey; } img.selected { border-color: red; }
<img src="https://picsum.photos/100" id="TAG1"/> <br/> <img src="https://picsum.photos/100" id="TAG2"/> <form action="https://website.com/business/" method="get"> <input type="submit" value="View Selected"/> </form>