nerdexam
Microsoft

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…

Perform Troubleshooting and Error Handling

Question

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 reference only. 01 <form name = "orderForm" action = "#" method = "post"> 02 <select name = "heatIndex" required> 03 <option>Mild</option> 04 <option>Medium</option> 05 <option>Spicy</option> 06 </select> 07 <button onclick = "checkWarning()">Order</button> 08 </form> You create the following JavaScript code to display the warning. 09 function checkWarning() { 10 var option = document.forms.orderForm.heatIndex; 11 if (option == "Spicy") { 12 alert("Spicy food: Good Luck!"); 13 } 14 } When you choose spicy and click Order, the warning fails to display. You need to solve this problem.

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

#DOM access#form elements#debugging#value property

Community Discussion

No community discussion yet for this question.

Full 98-382 Practice