Member-only story

Adding Multiple Values to Radio Buttons

Erika in Glasses
2 min readOct 27, 2016

--

Last week, on Wednesday, we hit the half way point for the bootcamp. We also started working with APIs. And continued working with JavaScript.

For my project, I wanted to use the LCBO API to sort out what beer people should take camping based on the chocolate type. But I ran into a couple issues with lagers begin returned the most, they take up about 80% of the results on the first page. I worked out how to get the first three pages to load, which helped a lot, but still left me with 20+ results for lagers and 4 for ciders.

I decided to change how I was planning to match the chocolate types to beer types and went with matching to the style value, not the beer type. But it was formatted as “one & two” for each beer. So I split this into three parts, and ran what the user selects against object 0 or object 2.

for (var i = 0; i < beerApp.preferredStyle.length; i = i + 1){
if (beerApp.preferredStyle[i] === brokenStyle[2] ||
beerApp.preferredStyle[i] === brokenStyle[0]){
return beerResults;
}
}

See the code in action:

But this meant I had way too many buttons and still limited results for certain selections. I started wondering how you could add multiple values to one radio button, so that it would return results that match either of options.

This lead me to thinking about making the radio button values related to an array of options, which looks like this:

if ($("input[name=style]:checked").val() === "one"){
beerApp.preferredStyle = ["Fruity","Floral"]
} else if ($("input[name=style]:checked").val() === "two") {
beerApp.preferredStyle = ["Hoppy","Spicy"]
} else if ($("input[name=style]:checked").val() === "three") {
beerApp.preferredStyle = ["Light"]
} else if ($("input[name=style]:checked").val() === "four") {
beerApp.preferredStyle = ["Medium"]
} else {
beerApp.preferredStyle = ["Full","Dark","Roasted"]
}

Depending on which label the user picks, my javascript takes the array that matches that value, runs it through the for statement above, and returns all the beers that match any of the objects in the array.

*Note the buttons do not appear in the same order on the website as they do in my code, I moved them around to match chocolate flavours from Milk to Dark, plus fruity.

--

--

Erika in Glasses
Erika in Glasses

Written by Erika in Glasses

Web developer. Twitch Affiliate (erikainglasses). Youtuber. Olympic lifter. I write about code and streamer.

No responses yet

Write a response