In this article, you will learn how to show/hide a textbox based on the user’s selection of the drop-down menu. If the user selects yes from the drop-down menu, the text box will appear.

Show/Hide a TextBox in Javascript and jQuery

If the selection is No

If the selection is Yes

HTML

<form>
   <div id="drop-down" name="drop-down">
      <label for="travel">Have you visited Europe before? </label>
      <select name="travel" id="travel" onChange=showHide()>
         <option value="1">Yes</option>
         <option value="0" selected>No</option>
      </select>
   </div>
   <div name="hidden-panel" id="hidden-panel">
      <label for="country">Name of the country you visited: </label>
      <input type="text" name="country" id="country"/>
   </div>
</form>

CSS

#hidden-panel {
	display: none;
}

body {
	font-family: 'Montserrat', sans-serif;
}

div {
	padding: 5px;
	margin: 5px;
}

input,
select,
option {
	padding: 5px;
}

select {
	width: 100px;
}

Show/Hide TextBox using JavaScript

function showHide() {
    let travelhistory = document.getElementById('travel')

    if (travelhistory.value == 1) {
        document.getElementById('hidden-panel').style.display = 'block'
    } else {
        document.getElementById('hidden-panel').style.display = 'none'
    }
}

The example simply evaluates the value of the drop-down menu and sets to display the value of the hidden-panel depending on it.

Now do the same example in jQuery.

Show/Hide TextBox using jQuery

To use jQuery, you need to link to jQuery first. You can download the jQuery from the official website or can use the CDN link (recommended):

https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js

The HTML and CSS code remains the same.

jQuery

<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" > </script> 
<script>
    $(document).ready(function() {
        $("#travel").change(function() {

            if ($("#travel").val() == 1) {
                $("#hidden-panel").show()
            } else {
                $("#hidden-panel").hide()
            }
        })
    }); 
</script>

When the user selects an option from the drop-down menu, the change event will be triggered. You can use this opportunity to assess the value of the drop-down and show/hide text box according to the selection made by the user.

If you are new to JavaScript and don’t understand what is going on, you can always use console.log() method to see the values.

Related Articles

Last modified: September 10, 2019

Comments

Write a Reply or Comment

Your email address will not be published.