Toggle the visibility of a div depending on the user's selection

My HTML select element has a few options to choose from:

 <select class="form-control" data-val="true" data-val-number="The field
 CodeSetup must be a number." id="CodeSetup" name="CodeSetup">
<option selected="selected" value="0">AllCodes</option>   
<option value="1">ClientCodes</option>
<option value="2">EmployeeClass</option>
</select>

<div id="eeclass">
      <div class="row setup-code-edit">
       <label class="control-label col-md-5 label-blue-small" for="EEClassCodes">EEClassCodes</label>
         <div class="col-md-7">
  <input class="form-control" id="EEClassCodes" name="EEClassCodes" type="text" value="">
         <span class="field-validation-valid text-danger" data-valmsg-for="EEClassCodes" data-valmsg-replace="true"></span>
                            </div>
                        </div>
                    </div>

I have created a script that will display a specific field when a certain option is selected in the dropdown menu. Here's how it works:

 $(document).ready(function() {
        $('#eeclass').hide();
        $("#CodeSetup").change(function () {
            $('#eeclass').show();
        });

    })

However, I noticed that the field is always displayed whenever an option is selected, regardless of which one. I need to make it so that the field only shows up when "EmployeeClass" is chosen (value="2"). Additionally, I want the field to disappear when another option is selected instead. I tried using toggle but couldn't get it to work correctly.

Answer №1

Is your intention to display it only when the selection value is 2?

$(document).ready(function() {
        $('#eeclass').hide();
        $("#CodeSetup").change(function () {
            if($(this).val() == 2) {
               $('#eeclass').show();
            } else {
               $('#eeclass').hide(); /* It will remain hidden if the value is not 2 */
            }
        });

    })

Answer №2

Indeed, you are interested in toggling functionality. Give this a try:

$("#CodeSetup").change(function () {
  $('#eeclass').toggle($(this).val()==2); // or this.value==2
});

Answer №3

Give it a go!

<select class="form-control" data-val="true" data-val-number="The field
     CodeSetup must be a number." id="CodeSetup" name="CodeSetup">
    <option selected="selected" value="0">AllCodes</option>   
    <option value="1" data-div="eeclass0">ClientCodes</option>
    <option value="2" data-div="eeclass1">EmployeeClass</option>
    </select>

along with this snippet of javascript

 $(document).ready(function() {
        $('.EEClassCodes').hide();
        $("#CodeSetup").change(function () {
            $ ( '#'+$(this).attr('data-div') ).show();
        });

    })

Answer №4

To ensure that the selection is always updated, the code hides it every time there is a change in the select options. If the user initially chooses 2 and then changes their mind to select option 1, the element will be hidden. However, if the selection is indeed 2, it will be shown.

$(document).ready(function() {
    $('#eeclass').hide();
    $("#CodeSetup").change(function () {
        $('#eeclass').hide(); // Always hide on change
        if($(this).val() == 2) {
             $('#eeclass').show(); // Show only if value is 2
        }
    });
});

Alternatively, you could choose to hide the element in all other cases.

$(document).ready(function() {
    $('#eeclass').hide();
    $("#CodeSetup").change(function () {
        if($(this).val() == 2) {
             $('#eeclass').show(); // Show if value is 2
        }
        else {
            $('#eeclass').hide(); // Hide if value is not 2
        }
    });
});

Both approaches have their merits and can be subject to debate.

Answer №5

Why not give this a shot?

Markup Language

      <head>
        <script data-require="jquery@*" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
        <link href="style.css" rel="stylesheet" />
        <script src="script.js"></script>
      </head>

      <body>
        <select name="CodeSetup" id="CodeSetup" data-val-number="The field
     CodeSetup must be a number." data-val="true" class="form-control">
          <option value="0" selected="selected">AllCodes</option>
          <option value="1">ClientCodes</option>
          <option value="2">EmployeeClass</option>
        </select>
        <input type="text" value="" name="EEClassCodes" id="EEClassCodes" class="form-control" />
      </body>

    </html>

Custom JavaScript (JS)

    $(document).ready(function(){

      $('#EEClassCodes').hide();

      $("#CodeSetup").change(function(){
            if(parseInt($(this).val()) === 2){
              $('#EEClassCodes').show();
            }
            else{
              $('#EEClassCodes').hide();
            }
      });


    })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you use $_REQUEST in PHP to fetch an array of inputs for database insertion?

I have a webpage where I am utilizing AJAX to transfer inputs to a PHP file for database entry. The following is my JavaScript code: var pageLoaded = function () { var submitButton = document.getElementById("submit"); if (submitButton) { submitButton. ...

What is the best way to wrap Bootstrap 5 columns according to the text inside them?

When using Bootstrap 5, is there a way for Bootstrap to arrange two rows with one column each if the text in one cell is wrapped and contains "My text" or "My other text"? <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi ...

Using Angular 5 to link date input to form field (reactive approach)

I'm encountering an issue with the input type date. I am trying to bind data from a component. Below is my field: <div class="col-md-6"> <label for="dateOfReport">Data zgłoszenia błędu:</label> <input type="date" formC ...

Save the text entered into an input field into a Python variable

Is there a way to retrieve the text from input fields that do not have a value attribute using Selenium? The issue is that these fields are populated automatically, possibly through JavaScript, upon page load and the text does not appear in the HTML source ...

"Unprecedented occurrence of double events firing in jQuery's sortable and draggable functions

I've implemented some drag and drop code that is functioning properly. However, I have encountered a minor issue. Whenever I add an alert within the drop function for debugging purposes (e.g. alert(draggedItem.text());), it triggers the alert twice wh ...

Change the font awesome class when the button is clicked

Here is the code I have in this jsfiddle. I am trying to change the font awesome icon on button click using javascript, but it doesn't seem to be working. I am new to javascript, so please pardon me if this is a silly question. HTML <button id="f ...

Update the second dropdown automatically based on the selection in the first dropdown menu

I need assistance with creating two dropdown menus that are linked, so when an option is selected in the first menu, it automatically changes the options available in the second menu. Both menus should be visible at all times. I have set up a fiddle to pr ...

Tips for avoiding a form reload on onSubmit during unit testing with jasmine

I'm currently working on a unit test to ensure that a user can't submit a form until all fields have been filled out. The test itself is functioning correctly and passes, but the problem arises when the default behavior of form submission causes ...

Adding material-ui library to a stylesheet

Can I include @material-ui/core/colors/deepOrange in my CSS file? I want to import this library and use it as shown below: import deepOrange from '@material-ui/core/colors/deepOrange'; import deepPurple from '@material-ui/core/colors/deepPu ...

Tips for verifying if an ASP.Net File Upload Control contains a file using JQuery

Currently, I'm working on a custom validator where I need to validate if a file has been uploaded using the asp.net File Upload Control. Here's what I have so far: function validate(sender, args) { if ($('#<%= hdnID.ClientID%>&ap ...

Tips on embedding an HTML page within another HTML page by utilizing a custom directive in AngularJS

I am looking to utilize custom directives in order to insert one HTML page into another. How can I achieve this? The custom directive code is as follows: (here is the .js file) fbModule.directive('fbLogin', function(){ return { ...

Using html as a template parameter in django

When passing HTML to my template, I am using the following code: passDict["problemText"] = <p> Some html</p> return render(response,'main/base.html',passDict). However, when trying to display {{problemText}} in my HTML file, I only se ...

Guide on implementing a date selector for each button/option clicked using Vue.js

My experience with Vuejs is still fresh, and I've incorporated 3 buttons named chart1, chart2, and chart3. Whenever any of these buttons are clicked, I want a Date selection to appear in a radio type format. You can see an example below: https://i.ss ...

Issue with Ajax post redirection back to original page

I'm facing an issue with my ajax call where I send multiple checkbox values to a php file for processing and updating the database. The post request and database updates are successful, but the page doesn't return to the calling php file automati ...

Navigating through a JSON object created from a Python dictionary in JavaScript

When working on a django app, I have encountered an issue with returning JSON data on a jQuery ajax call: { "is_owner": "T", "author": "me", "overall": "the surfing lifestyle", "score": "1", "meanings": { "0": "something", ...

Issue encountered with the ".replaceWith" method not functioning properly when incorporating the "nl2br()" function and inserting the "Enter" key within database text

I am facing an issue with editing text displayed from the database. When the text is in one line, the "Edit Text" button works perfectly. However, if I use an enter to create a new line in the text, the editing functionality does not work as expected. To ...

Is there a way to limit HTML wrapping to 79 characters in TextMate?

I'm currently using TextMate to work on my HTML projects. When I select View > Wrap > 79 characters for certain types of content, it wraps at 79 characters as expected. But when it comes to working with HTML, this feature doesn't seem to ...

Tooltips experience issues when interacting with elements that do not utilize the :active state

$(function () { $('[data-toggle="tooltip"]').tooltip() }) <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" ...

Is it possible to deactivate an anchor tag based on the result of a conditional statement that returns a string?

I've created an anchor tag (not a button) with text that redirects me to another page <StyledTableCell align="center"> <Link href={`/races/results/${race.id}`}>{race.race_name}</Link> </StyledTableCell> There is a ...

Utilize JSON data loading instead of directly embedding it onto the page for improved website

I've integrated Mention.js into my website, allowing a dropdown list of usernames to appear when "@" is typed in a designated textarea. <textarea id="full"></textarea> While it's functioning well, the examples provided only show how ...