98-382 · Question #5
You are creating a web page that allows customers to choose how hot their spice is. If they choose spicy, a warning should be displayed. You create the following form. Line numbers are included for…
The issue is on line 11: if (option == "Spicy"). The variable option refers to the entire HTMLSelectElement object (the <select> tag itself), not the text content of the currently selected option. Comparing an HTML element object directly to a string will always result in…
Question
Explanation
The issue is on line 11: if (option == "Spicy"). The variable option refers to the entire HTMLSelectElement object (the <select> tag itself), not the text content of the currently selected option. Comparing an HTML element object directly to a string will always result in false.
To get the text of the currently selected option, you need to access the text property of the selected option within the select element. This can be done using option.options[option.selectedIndex].text.
Here's the corrected JavaScript code:
function checkWarning() {
var selectElement = document.forms.orderForm.heatIndex;
var selectedOptionText = selectElement.options[selectElement.selectedIndex].text;
if (selectedOptionText == "Spicy") {
alert("Spicy food: Good Luck!");
}
}
Alternatively, for a more concise change to the original code:
function checkWarning() {
var option = document.forms.orderForm.heatIndex;
if (option.options[option.selectedIndex].text == "Spicy") { // Corrected line
alert("Spicy food: Good Luck!");
}
}
Topics
Community Discussion
No community discussion yet for this question.