What could be causing my div to not appear when using jquery's show function?

I'm dealing with HTML code that looks like this:

<div id="answerTypeSection" style="visibility: hidden">
  <div class="row">
      <div class="col-md-2">adfadfafasdfasdfas</div>
 </div>
 <label class="control-label">adfa</label>
  adfaf
</div>

<select id="answerType" class="form-control">
                            <option></option>
                            <option>Text</option>
                            <option>A or B (Boolean)</option>
                            <option>Numeric</option>
                            <option>Photo</option>
                            <option>Files</option>
                            <option>Multi (combo)</option>
                        </select>

Now, in my JavaScript...

$("#answerType").change(function () {
    var answerType = $('#answerType').val();
    console.log('in');
    var showType;

    switch(answerType) {
        case "Numeric":
            showType = "N";
            console.log('numeric');
            $("#answerTypeSection").show();
            break;
        default:
            showType = "what";
            // hide?
            console.log('hide');
            $("#answerTypeSection").hide();
            break;

    }
 // required 
});

The issue here is that 'in' and 'numeric' are logged in the console, but answerTypeSection does not seem to show up. Shouldn't it be visible?

Answer №1

Retrieve the text from the selected option element,

$("#answerType").change(function() {
  var answerType = $('#answerType option:selected').text(), showType;
  switch (answerType) {
    case "Numeric":
      showType = "N";
      $("#answerTypeSection").show();
      break;
    default:
      showType = "what";
      $("#answerTypeSection").hide();
      break;
  }
});

CHECK IT OUT

In addition, using .show() and .hide() may not function properly with visible:hidden. It is essential to use display:none instead. If you prefer using the visible property, you can modify it using .css().


An efficient approach for handling this scenario would be assigning a value attribute to the options within your select element,

<select id="answerType" class="form-control">
  <option value="">---</option>
  <option value="Text">Text</option>
  <option value="A or B (Boolean)">A or B (Boolean)</option>
  <option value="Numeric">Numeric</option>
  <option value="Photo">Photo</option>
  <option value="Files">Files</option>
  <option value="Multi (combo)">Multi (combo)</option>
</select>

To handle the above HTML structure, adjust your JavaScript as follows:

$("#answerType").change(function() {
  var answerType = $(this).val();
  var showType;
  switch (answerType) {
    case "Numeric":
      showType = "N";
      $("#answerTypeSection").show();
      break;
    default:
      showType = "what";
      $("#answerTypeSection").hide();
      break;
  }
});

SEE DEMO

Answer №2

When modifying the CSS property <span style="color: blue;">visibility</span>, it is best practice to use CSS as shown below.

$("#answerTypeSection").css("visibility", "visible");

Answer №3

The method .show() alters the display property of an element, while you are currently using visibility:hidden to conceal it, indicating a variance in approach.

Answer №4

It appears that you are utilizing the .show() function to manipulate the display property of an element, while having set visibility:hidden in the corresponding div. Although your function is functioning correctly, you might want to consider using a different method.

You could either employ .css('visibility', 'visible'); or include style="display:none" directly in the div tag.

HTML

<div id="answerTypeSection" style="display: none">
  <div class="row">
    <div class="col-md-2">adfadfafasdfasdfas</div>
  </div>
  <label class="control-label">adfa</label>
  adfaf
</div>

<select id="answerType" class="form-control">
  <option></option>
  <option>Text</option>
  <option>A or B (Boolean)</option>
  <option>Numeric</option>
  <option>Photo</option>
  <option>Files</option>
  <option>Multi (combo)</option>
</select>

JS

$("#answerType").change(function() {
  var answerType = $('#answerType').val();
  console.log('in');
  var showType;

  switch (answerType) {
    case "Numeric":
      showType = "N";
      console.log('numeric');
      $("#answerTypeSection").show();
      break;
    default:
      showType = "what";
      // hide?
      console.log('hide');
      $("#answerTypeSection").hide();
      break;

  }
  // required 
});

Example : https://jsfiddle.net/yped7no0/

Answer №5

The visibility of your div is not being displayed due to the attribute visible in the code below:

<div id="answerTypeSection" style="visibility: hidden">

To resolve this issue, simply update the code as follows:

<div id="answerTypeSection" style="display: none">

Check out this helpful JSFiddle demo for more information

Your code wasn't working because JQuery's show() method only modifies the display attribute and not the visible attribute that you had used previously.

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

What is the method to retrieve results using 'return' from NeDB in vue.js?

Seeking assistance on retrieving data from NeDB within a method in a .vue file using electron-vue. Currently, I am aware that the data can be stored in a variable, but my preference is to fetch it using 'return' as I intend to utilize the result ...

Utilizing two visuals within the <picture> srcset

Is there a way to include two images on the desktop version (one on the right and one on the left) within the picture tag that replaces the mobile version image? I attempted it but it didn't work as expected. <picture> <source medi ...

The <script> element failed to close correctly

Within my default.jspx file, which serves as the foundational layout for the page, I am attempting to import several jQuery libraries. The code snippet looks like this: <head> ... <spring:url value="/resources/js/lib/jquery-1.9.1.min.js" ...

Cannot find WoopraTracker within the custom event data

I am currently working on implementing Woopra custom event data upon page load by following their guidelines. I have attempted to push events when the page is ready, however, it keeps returning an error that woopratracker is not defined. Strangely, when ...

Angular - Showcasing Nested Objects in JSON

I am experimenting with using angular ngFor to iterate through this data: Link: Although I can successfully retrieve the data by subscribing to it, I encounter an issue when trying to display attributes that contain objects. The output shows as [object O ...

Is it possible to change text dynamically with an input box using JavaScript?

Is there a way to use JavaScript to create two input boxes for text replacement? Instead of constantly editing code to replace different text, I am looking for a simple user interface with Input Box A, Input Box B, and a button. The first input box will ...

Button located beneath or above each individual image within the *ngFor loop

With the *ngFor loop, I am able to populate images but now I want to include a button below or on each image. Unfortunately, my CSS knowledge is limited. Below is the code I have: HTML Code <div class="container"> <div ...

What is the best way to determine the range in which the value falls?

Currently, I am working on validating whether a User has the required karma (reputation) to perform certain actions, such as placing a bid on an item. The karma value falls within the interval [-25; 100]. Additionally, it is noted that as a user accumulate ...

Developing Webpart Postback logic in C# script

I am currently facing challenges with SharePoint webparts programming. I am unsure about how to trigger a postback for an object at a specific time. I have come across suggestions to use "javascript" for this purpose, but I am having trouble understanding ...

Notification (jQuery) failing to display user messages

Is there a way to retrieve the post title and display it in a notification? The notification's title is extracted from a form and shown in the notification. When the user clicks the submit button, the system captures the duration and title, displaying ...

Encountering an error message saying "assignment to undeclared variable"

I'm attempting to incorporate a react icon picker from material-ui-icon-picker However, I keep encountering an error stating "assignment to undeclared variable showPickedIcon" edit( { attributes, className, focus, setAttributes, setFocus, setState ...

The absence of FormData.entries in submit is a limitation of the Vue framework

I recently created a Vue-App that consists of a simple form with just one <input name"surname"> and a <button type="submit">. The use case is to input "myname" and submit the form. However, when I initialize new FormData( ...

retrieve the value of a specific key using JSON stringify

[{"displayorder":"1","menuname":"DashBoard","menuid":"5","menuurl":"dashboard.php"},{"displayorder":"3","menuname":"Accounting Module","menuid":"3","menuurl":""},{"displayorder":"4","menuname":"My Profile","menuid":"4","menuurl":"myprofile.php"},{"displayo ...

Displaying a pop-up message in Rails upon modifying a Model

Would it be feasible to implement the ActiveRecord Callbacks before_create after_create before_save after_save before_destroy after_destroy in order to showcase notifications to the user using jQuery? Could someone possibly share an example?? Appreci ...

Is it possible to load HTML content within a Sweet Alert pop-up

Below is the code I am using to call Swal: window.swal({ title: "Checking...", text: "Please wait", imageUrl: "{{ asset('media/photos/loaderspin.gif') }}", showConfirmButton: false, allowOutsideClick: false }); $.ajax({ t ...

Error occurs when trying to map an array within an asynchronous function

Hey there, I have an array of objects with validation inside my async function (router.post()) and I need to map it before validating. Here is the approach I am taking: ingredients.map(({ingredient, quantity})=>{ if(ingredient.trim().length < 1 | ...

Addressing the delay of "Rasterize Paint" on mobile devices while implementing css3 opacity transitions

I'm currently working on a project that involves users navigating back and forth between modals. To achieve this, I decided to use CSS transitions to change the opacity from 0 to 1. However, I've encountered some issues with slow transitions. So ...

Guide to filling out select dropdowns in HTML with information from a database

I'm new to PHP and HTML, so please be patient with me. I've been attempting to populate a select box using data from a MySQL database, but all I see is an empty textbox. Here's my current code: <select name="cargo"> <?php ...

Understanding the mechanism of callback function in NodeJS within the context of routes and controllers

Trying to grasp the concept of callbacks and puzzled by the recurring issue TypeError: callback is not a function Here's my router setup: // getPriceRouter.js router.post('/getPrice', function(req, res) { priceController.getPrice(req, ...

Assign the value of the selected option to the ng-model instead of the displayed text

When creating a new user, I am collecting user input. Users have the option to select their state from a dropdown menu. I am looking to save the state ID instead of the state name when the user makes a selection. How can I assign the state ID to the newSit ...