The problems:
- Alert box when a radio button is not selected, it does not work properly.
- After clicking on submit button, the 'cost' in the alert box says NaN, which I don't want.
And try to keep the HTML code as provided below as much as possible.
function calculateCost() {
var radioButton;
var pet;
var colour;
var cost = 0;
var selectedPet = ["Cat", "Dog", "Rabbit"];
var selectedColour = ["Black", "Gold", "White"];
for (var i = 1; i <= 3; i++) {
radioButton = document.getElementById(selectedPet[i - 1]);
if (radioButton.checked == true) {
pet = selectedPet[i - 1];
cost += parseInt(radioButton.value);
//alert(parseInt(radioButton.value));
} else if (document.getElementById(selectedPet[i]).null);
alert("You did not select a pet")
}
for (var i = 1; i <= 3; i++) {
radioButton = document.getElementById(selectedColour[i - 1]);
if (radioButton.checked == true) {
colour = selectedColour[i - 1];
cost += parseInt(radioButton.value);
//alert(parseInt(radioButton.value));
} else if (document.getElementById(selectedColour[i]).null);
alert("You did not select a colour")
}
cost = selectedPet.value * selectedColour.value;
alert("You have selected a " + pet + " and the colour selected was " + colour + ", the total cost is $" + cost);
}
<h1> Adopt a pet </h1>
<form>
<p>Choose a type of pet:
<br>
<input type="radio" id="Cat" name="pet" value="200"><label for="cat">Cat</label>
<br>
<input type="radio" id="Dog" name="pet" value="200"><label for="dog">Dog</label>
<br>
<input type="radio" id="Rabbit" name="pet" value="20"><label for="rabbit">Rabbit</label>
<br>
</p>
<p>Choose the colour of pet:
<br>
<input type="radio" id="Black" name="colour" value="80"><label for="black">Black</label>
<br>
<input type="radio" id="Gold" name="colour" value="100"><label for="gold">Gold</label>
<br>
<input type="radio" id="White" name="colour" value="90"><label for="white">White</label>
<br>
</p>
<p><input type="button" value="Submit" onClick="calculateCost();">
</form>