I’m trying to build out a test website that basically says: if you select the peanuts checkbox, here’s a peanut free website. If you select cashews, here’s a cashew free website. If you select both, here’s a peanut and cashew free website. (In the future, I would add other checkboxes as well for other foods, and then do various combinations) I’m getting stuck on the last part, however – trying to return unique info if both checkboxes are selected.
Here’s the code I put together. Without the last else if statement, it works. But I’m not sure what I need to do with the last else if to make it function fully. Appreciate any guidance here!
function myFunction() {
if (document.getElementById("peanuts").checked) {
document.write(
"<p> You have selected Peanuts. Here's a peanut-free recipe:"
);
} else if (document.getElementById("cashews").checked) {
document.write(
"<p> You have selected Cashews. Here's a cashew-free recipe:"
);
} else if (document.getElementById("dairy").checked) {
document.write(
"<p> You have selected Dairy. Here's a dairy-free recipe:"
);
} else if (
document.getElementById("peanuts").checked &&
document.getElementById("cashews").checked
) {
document.write("<p> You have selected Both. Here's a nut-free recipe:");
}
}
<input type="checkbox" name="peanuts" id="peanuts" />Peanuts<br />
<input type="checkbox" name="cashews" id="cashews" />Cashews<br />
<input type="checkbox" name="dairy" id="dairy" />Dairy<br />
<button id="myButton" type="button" value="getValue" onclick="myFunction()">
Get Value
</button>
3
Answers
instead of writing the if condition on the value of checked, we can store it in a variable.
Store all the .checked() values in a variable.
Then check if any combination of two values are true.
Let me know if you need the code for it.
this is because the order of execution just needs to be reversed:
You can find all selected checkboxes with a query:
and prepare output based on what is selected.