Assigning variables using checkbox

85 Views Asked by At

Ran into errors while trying to use a checkbox to assign variables:

WARNING: Line: 20: The checkbox() id parameter refers to an id ("nutBox") which already exists.
WARNING: Line: 23: The checkbox() id parameter refers to an id ("dairyBox") which already exists.
WARNING: Line: 26: The checkbox() id parameter refers to an id ("noneBox") which already exists.

I am trying to create a simple decision-making app for school that decides what you should eat based off of your hunger, allergies, and dietary restrictions (e. vegetarian).

Relevant code:

var allergy;
    
if (checkbox("nutBox", true)) {   // Line 20
  allergy = "nut";
}

if (checkbox("dairyBox", true)) { // Line 23
  allergy = "dairy";
}

if (checkbox("noneBox", true)) {  // Line 26
  allergy = "none";
}
1

There are 1 best solutions below

0
Kirtan Desai On

I think you are using the checkbox function incorrectly. According to the App Lab documentation for checkbox, the checkbox function is used to make a new checkbox. Hence, in your code, you were making new checkboxes causing you to get an error that a checkbox with the id already exists.

What you should do instead, is use the getChecked function.

var allergy;
    
if (getChecked("nutBox")) {   
  allergy = "nut";
}

if (getChecked("dairyBox")) { 
  allergy = "dairy";
}

if (getChecked("noneBox")) { 
  allergy = "none";
}

Also, since you only want one selection from the checkboxes, you should use a radio button instead of checkbox.

However, one can have multiple allergies. So remove the noneBox and instead store the allergies in an array.

And for the next time you want to ask a question on stackoverflow, first explain what programming language are you using. Good luck :)