How can I display a pre-existing div with a dropdown button?

I have individual div elements for each type of clothing item (shirt, pant, suit) that I want to display when the corresponding service is selected. This means that when I click on one of them, only that specific div will be shown. I am looking for a solution using JQuery. TIA

$(function(){
          $('#selectService').change(function() {
            alert($(this).val());
            // I want to display the respective div(s) instead of showing alerts, based on which option is clicked
          }); 
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
          <div id="orderClone" class="row">
            <div class="table-responsive">
              <table class="table table-striped">
                <tr>
                  <th>Service</th>
                </tr>
                <tr>
                  <td>
                    <select id="selectService" name="service[]" class="form-controlservice">
                      <option disabled="" selected="">Select Service</option>
                      <option id="one" value="shirt">Shirt</option>
                      <option value="pant">Pant</option>
                      <option value="suit">Suit</option>
                    </select>
                  </td>
                </tr>
              </table>
            </div>
          </div>
          <div class="col-md-4">
            <h4><b>Shirt</b></h4>
            <hr/>
            <div class="form-group required">
              <label class="control-label">Body</label>
              <input type="text" class="form-control" name="body" />
            </div>
            <div class="form-group required">
              <label class="control-label">Shoulder</label>
              <input type="text" class="form-control" name="shoulder" />
            </div>
            <div class="form-group required">
              <label class="control-label">Neck</label>
              <input type="text" class="form-control" name="neck" />
            </div>
          </div>
          <div class="col-md-4">
            <h4><b>Pant</b></h4>
            <hr/>
            <div class="form-group required">
              <label class="control-label">Length</label>
              <input type="text" class="form-control" name="length" />
            </div>
            <div class="form-group required">
              <label class="control-label">Thigh</label>
              <input type="text" class="form-control" name="thigh" />
            </div>
          </div>
          <div class="col-md-4">
            <h4><b>Suit</b></h4>
            <hr/>
            <div class="form-group required">
              <label class="control-label">Name</label>
              <input type="text" class="form-control" name="length" />
            </div>
            <div class="form-group required">
              <label class="control-label>Name</label>
              <input type="text" class="form-control" name="thigh" />
            </div>
          </div>
        

I tried using change() for each service in the select element but couldn't figure out how to include the div(s) for the shirt. Ideally, when I select 'shirt' from the service dropdown, I want the 'shirt' div to be displayed.

Answer №1

To begin, the first step is to conceal all the fields that will be toggled between. This can be achieved by applying a class that hides these elements by default. Additionally, this class simplifies the process of selecting all elements simultaneously.

Subsequently, it is essential to establish a connection between the <select> options and the fields intended for toggling. In this case, the selected value can correspond to the id of the field targeted for toggling.

Upon selecting a new item, utilize the designated class for selecting toggleable elements to .hide() all hidden fields. Following this, employ the selected element to .show() the desired field.

If you have any queries or require further clarification, feel free to reach out.

$(function() {
  $('#selectService').change(function() {
    /* Conceal all fields when a new item is selected */
    $('.hidden-fields').hide();

    /* Identify the selected field and display it */
    var $target = $(this).val();
    $('#' + $target).show();
  });
});
/* Set default visibility to hidden for all fields */

.hidden-fields {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="orderClone" class="row">
  <div class="table-responsive">
    <table class="table table-striped">
      <tr>
        <th>Service</th>
      </tr>
      <tr>
        <td>
          <select id="selectService" name="service[]" class="form-control service">
            <option disabled="" selected="">Select Service</option>
            <option id="one" value="shirt">Shirt</option>
            <option value="pant">Pant</option>
            <option value="suit">Suit</option>
          </select>
        </td>
      </tr>
    </table>
  </div>
</div>
<div class="col-md-4 hidden-fields" id="shirt">
  <h4><b>Shirt</b></h4>
  <hr/>
  <div class="form-group required"> <label class="control-label">Body</label>
    <input type="text" class="form-control" name="body" />
  </div>
  <div class="form-group required">
    <label class="control-label">Shoulder</label>
    <input type="text" class="form-control" name="shoulder" />
  </div>
  <div class="form-group required">
    <label class="control-label">Neck</label>
    <input type="text" class="form-control" name="neck" />
  </div>
</div>
<div class="col-md-4 hidden-fields" id="pant">
  <h4><b>Pant</b></h4>
  <hr/>
  <div class="form-group required"> <label class="control-label">Length</label>
    <input type="text" class="form-control" name="length" />
  </div>
  <div class="form-group required">
    <label class="control-label">Thigh</label>
    <input type="text" class="form-control" name="thigh" />
  </div>
</div>
<div class="col-md-4 hidden-fields" id="suit">
  <h4><b>Suit</b></h4>
  <hr/>
  <div class="form-group required"> <label class="control-label">Name</label>
    <input type="text" class="form-control" name="length" />
  </div>
  <div class="form-group required">
    <label class="control-label">Name</label>
    <input type="text" class="form-control" name="thigh" />
  </div>
</div>

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

Rotating and scaling an image simultaneously using CSS3

I am feeling very puzzled. Why am I unable to simultaneously scale and rotate? Despite my attempts, it seems to be not working: .rotate-img{ -webkit-transform:scale(2,2); -webkit-transform:rotate(90deg); margin-left:20%; margin-top:10%; } ...

Error detecting 403 status code during jquery AJAX request

My current code is set up to trigger an application on a different user's machine through port 9084, as I do not have access to a DEV server. The application in question is written in JAVA and I am trying to initiate it from my ASP.Net application (wh ...

Changing an ng-repeat filter following the manual update of a text input

Utilizing jQuery auto-complete to automatically populate values as users type into a text input. <input type="text" ng-model="tags" name="tags" id="tags" value="" /> Subsequently, the ng-repeat is filtering content based on the entered text <di ...

Creating a jQuery countdown script

Is it possible to easily convert the function below into jQuery and still maintain the ability to call multiple instances of the countdown? This particular function receives a server time echoed by the server and then initiates a countdown to the specifie ...

Malfunction in triggering events within an Ajax Magnific popup feature

I'm trying to load a page within a magnific popup using ajax: $("#operator").magnificPopup({ delegate: 'a.edit', mainClass: 'mfp-fade', closeBtnInside: true, removalDelay: 300, closeOnContentClick: false, t ...

The onTableChange function in Mui-Datatable does not seem to be functioning properly when attempting to

Utilizing mui-datatable, I came across an official example on codesandbox where setState can be used on the tableState. You can check out the example here: https://codesandbox.io/s/trusting-jackson-k6t7ot?file=/examples/on-table-init/index.js handleTableIn ...

The level of transparency linked with text in a blockquote

I've spent hours on this and I'm completely lost. Even though I believe my code is correct, it keeps telling me it's wrong. I don't know where to go from here. The task requires adding a style rule for the blockquote element that chan ...

Managing Time Before Browser Refresh in AngularLearn how to monitor and examine the time remaining before

In my Angular web application, I am facing an issue where the user's login status is lost every time the browser is refreshed or reloaded. I want to implement a feature that allows the login status to remain active for a short period of time after the ...

Using Google's Closure Compiler to Optimize JSON Files

When dealing with a json string that is parsed and properties of the object are accessed using dot notation, a warning may be triggered by the google closure compiler stating that the property is not defined. To overcome this issue, one workaround is to c ...

Retrieve the access ID from the conn.query result

When I run a SQL query, I need to extract the primary key (id) of the event returned so I can use it in another SQL query. However, attempting to access it using result.insertId returns null for the event object. Even logging result.insertId only outputs ...

Redirecting the socket.io client to the Heroku service

Recently, I developed a real-time chat application using socket.io, Node.JS, and express. It was functional on my local server but now I want to connect it to an existing Heroku service instead. How can I achieve this? Once I tried the following code, va ...

Eliminating null values from arrays

Hello there! I'm currently working on inserting a list of locations into my database. $locations = array(); $locations = $_POST['loc']; $loc = implode(", ", $locations); However, when I insert the array into my database, the empt ...

First render does not define useEffect

Why am I experiencing an issue here? Whenever I attempt to retrieve data from my API, it initially returns undefined during the first render, but subsequent renders work correctly. const [data, setData] = useState([]) useEffect(() => { const fe ...

every cell should be painted a distinct hue

I need to create a 10x10 array in JavaScript and fill each cell in the 2D array with different colors using canvas. I have managed to do this part, but now I am stuck on how to check if each cell has a different color from its neighbors. Any suggestions ...

Struggling to understand JSON in joint.js?

I am trying to utilize the joint.js library to render a JSON data as a chart... let paper = new joint.dia.Paper({ el: $('#paper'), width: 600, height: 200, model: graph }); let graph = new joint.dia.Graph; let json = '{"em ...

When a user clicks on a button, AJAX and jQuery work together to initiate a setInterval function that continually

Currently, I have two scripts in place. The first script is responsible for fetching a specific set of child nodes from an XML file through AJAX and using them to create a menu displayed as a list of buttons within #loadMe. What's remarkable about thi ...

Utilize a JSON object with ChartJS for data visualization

Recently, I've been working with a REST API that returns historical data in the following format: { "2021-6-12": 2, "2021-6-13": 3, "2021-6-14" :1 } This data represents the count of measurements taken on each date ...

What is the best way to eliminate file extensions from hyperlinks in this particular scenario?

Looking for solution in editing a php gallery code to adjust hyperlink destination. This php gallery script generates a gallery from a folder of images which, when clicked on, opens a larger preview with a hyperlink. However, the issue is that the link in ...

Troubleshooting problems with data rendering in jQuery

Currently, my goal is to use JQuery to display a menu of checkboxes based on a specific template in a div. To enhance user experience, I have included a search box that will filter the menu items. However, there is an unusual issue occurring. When the men ...

JavaScript code using jQuery's ajax method is sending a request to a PHP server, but

Attempting to utilize jQuery ajax for PHP call and JSON return. The test is quite simple, but only receiving an empty object in response. No PHP errors appearing in the LOG File. jqXHR is recognized as an object with 'alert', yet not displayin ...