Show or Hide text box on dropdown selected index change event using HTML and JavaScipt

This HTML tutorial we will discuss, how to handle the dropdown selected index change event using JavaScript. Here we will see how to show or hide a comment box based on dropdown selected index change event using HTML and JavaScipt.

Show or Hide Comment box on dropdown selected index change event using HTML and JavaScipt

In one of the requirement, we had one drop-down list which has options like:

  • Happy
  • Satisfied
  • Sad

As per our requirement, we need to show a comment box when the user selects Sad from the dropdown list. Else the comment box should be hidden in the HTML form.

First, we are creating an HTML file. The HTML file contains the following code:

<!DOCTYPE html>
<html>
<scriptsrc="https://onlysharepoint2013.sharepoint.com/sites/Raju/tsinfo/SiteAssets/HtmlJsCssFiles/file.js"></script>
<body>
<h1>Suggestion Box</h1>
Choose an Option:   <select id="ddlSuggestion" onchange="GetSelectedTextValue(this)">
<option value="0">Happy</option>
<option value="1">Satisfied</option>
<option value="2" >Sad</option>
</select>
</br>
<textarea rows="4" cols="50" id="txtComments" style="display: none;" >
</textarea>
</body>
</html>

In script tag using src attribute, we have to give the path of JS file. In select option, we are giving the id named as”ddlSuggestion”

“GetSelectedTextValue(this)” is a function which is present in js file. When an item is selected in dropdown list, the “GetSelectedTextValue(this)”method will execute . We pass the current object (this) as a parameter in the function.

Below is the javascript function which we have written inside the .js file. And we are calling in the onchange event.

functionGetSelectedTextValue(ddlSuggestion) {
varselectedValue = ddlSuggestion.value;
if(selectedValue=="2")
{
document.getElementById("txtComments").style.display = ";
}
else
{
document.getElementById("txtComments").style.display = ‘none’;
}
}

First, we are retrieving the dropdown list selected value by using the below line.

var selectedValue = ddlSuggestion.value;

Then we are comparing and if the condition satisfies we are displaying the comment box like below:

document.getElementById("txtComments").style.display = ";

else we are hiding the comment box like below:

document.getElementById("txtComments").style.display = 'none';

You may like following JavaScript tutorials:

In this article, we are discussing how to handle the dropdown selected index change event in HTML using JavaScript. We saw how to show or hide textbox based on dropdown selected index change event in HTML form.

Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

>