Ways to display or conceal table cells depending on dropdown selections

I have been working on a table that consists of 5 or 6 td elements. The data in the table is derived from 3 dropdown menus along with a Go button. When I enter values in all three dropdowns and click on Go, it displays the result in the table. However, the issue arises when I do not select a value in one or two of the dropdowns and keep it as null. In such cases, I don't want that particular column to show up in the table. I've been attempting to achieve this using JavaScript but haven't been successful so far. Here's the HTML code snippet:

$(document).ready(function() {
  $("#go").click(function() {
    var select1 = document.getElementById("select1").value;
    var select2 = document.getElementById("select2").value;
    var select3 = document.getElementById("select3").value; // Note: There was an extra semicolon here
  });

  if (select1 == null) {
    document.getElementByClass('select1td').style.display = none;
  }
  if (select2 == null) {
    document.getElementByClass('select2td').style.display = none;
  }
});
<select id="select1" name="select1" style="width: 190px; display: block;">
  <option selected value="" disabled="disabled">Select an option</option>
  <?php 
    $sql="SELECT DISTINCT name FROM tbl1 ";
            
    $result = mysql_query($sql);

    while ($row = mysql_fetch_array($result)) {
        
        echo "<option  class='name' value=' " . $row['name'] ."'>" . $row['name'] ."</option>";
        }
    ?>
</select>
<label>Lot Name</label>
<select id="select2" name="select2" style="width: 190px; display: block;">
  <option selected value="" disabled="disabled">Select an option</option>
  <?php 
    $sql="SELECT DISTINCT course FROM tbl1 ";
            
    $result = mysql_query($sql);

    while ($row = mysql_fetch_array($result)) {
        
        echo "<option  class='course' value=' " . $row['course'] ."'>" . $row['course'] ."</option>";
        }
    ?>
</select>

<!-- And there is also a third dropdown menu -->


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="select1td">
      <?php echo $row["name"]; ?>
    </td>
    <td class="select2td">
      <?php echo $row["course"]; ?>
    </td>
    <td class="select3td">
      <?php echo $row["reg"]; ?>
    </td>
</table>

Answer №1

I converted the original javascript code to jquery for you. By using if(myvalue), you can easily check for empty values. This is because javascript interprets an empty string as false. Another way to check for an empty value is by using if(myvalue !== '') which specifically checks if myvalue is not an empty string.

You also had your if statements written outside of the onclick event handler, causing the code to be executed on the ready event.

$(document).ready(function() {
  $("#go").on('click', function() {
    $('#select1').val() ? $('.select1td').show() : $('.select1td').hide();
    $('#select2').val() ? $('.select2td').show() : $('.select2td').hide();
    $('#select3').val() ? $('.select3td').show() : $('.select3td').hide();
  
    /* Here's an alternative notation if you prefer:

    if ($('#select1').val()) {
      $('.select1td').show();
    } else {
      $('.select1td').hide();
    }

    if ($('#select2').val()) {
      $('.select2td').show();
    } else {
      $('.select2td').hide();
    }

    if ( $('#select3').val()) {
      $('.select3td').show();
    } else {
      $('.select3td').hide();
    }
    
    */
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select1">
  <option value=''>no value</option>
  <option value='something'>value</option>
</select>

<select id="select2">
  <option value=''>no value</option>
  <option value='something'>value</option>
</select>

<select id="select3">
  <option value=''>no value</option>
  <option value='something'>value</option>
</select>

<button id="go">Go</button>

<table>
  <tr>
    <td class="select1td">select1td</td>
    <td class="select2td">select2td</td>
    <td class="select3td">select3td</td>
  </tr>
</table>

Answer №2

When using JQuery, you can utilize element.toggle();

Alternatively, in JavaScript you can use element.style.display.

If you encounter issues with the code snippet below:

document.getElementByClass('select1td').style.display=none; //incorrect

To target an element with a specific class, the correct syntax is as follows:

document.getElementsByClassName('select1td')[index].style.display=none;

As classes return arrays of elements, remember to specify an index starting from 0.

A more efficient approach would be to assign one class to multiple td elements:

<table>
<tr>   
<td class="selecttd"><?php echo $row["name"]; ?></td>
<td class="selecttd"><?php echo $row["course"]; ?></td>
<td class="selecttd"><?php echo $row["reg"]; ?></td>
</table>

You can then select each individual element like so:

document.getElementsByClassName('selecttd')[0.style.display=none;//first element
document.getElementsByClassName('selecttd')[0].style.display=none;//second element
document.getElementsByClassName('selecttd')[0].style.display=none;//third element

An even better solution involves utilizing document.querySelector(), which allows for flexible element selection by tag name, class, or id:

document.querySelector("td");//selects first td
document.querySelectorAll(".class")[2];//selects third element with class
document.querySelector("#id");//selects element by id

Your improved JavaScript code could be structured as shown below:

$(document).ready(function(){
      $("#go").click(function(){
 var select1=document.getElementById("select1").value;
  var select2=document.getElementById("select2").value;
   var select3=document.getElementById("select3").value;
   ;
      });

      if(select1==null){
document.querySelectorAll('selecttd')[0].style.display=none;
      }
      if(select2==null){
document.querySelectorAll('selecttd')[1].style.display=none;
      }
      }); 
  </script>

And in HTML:

<table>
<tr>   
<td class="selecttd"><?php echo $row["name"]; ?></td>
<td class="selecttd"><?php echo $row["course"]; ?></td>
<td class="selecttd"><?php echo $row["reg"]; ?></td>
</table>

An example using JQuery:

$(document).ready(function(){
      $("#go").click(function(){
 var select1=$(#select1").val;
  var select2=$(#select2").val;
   var select3=$(#select3").val;
   ;
      });

      if(select1==null){
$('.selecttd')[0].toggle();
      }
      if(select2==null){
$('.selecttd')[1].toggle();
      }
      }); 

I trust this information proves beneficial. Best of luck!

Answer №3

Give this a shot:

Just a heads up, it's best to avoid using mysql* functions as they are now deprecated. Opt for mysqli* instead.

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

Deactivate "When the viewModel attribute holds the phrase 'some text'"

I came across this answer on Stack Overflow regarding checking for a value in Knockout, but it seems to be outdated. I am attempting to achieve something like this: <li> <span data-bind="text: Subject"></span> <!-- ko if: Subjec ...

What could be causing the distance between the image and the navigation bar?

Hey there, I'm struggling with a pesky little gap that's sneaking in between an image and my navigation bar. I've exhausted all my usual tricks like setting inline-blocks on the ul and li levels, and trying to align everything left with text ...

Guide on how to make the parent scrollable once children are dynamically added

Do you know why the .wrap-max-height is not working properly? I am expecting it to be limited by 100vh - 108px and for .ins to be scrollable if needed. Any assistance would be greatly appreciated! $('button').on('click', function() ...

Objects saved in an array are still being overwritten

I'm currently tackling the challenge of saving objects in an array, but I'm facing an issue where the data is being overwritten instead of added. Any suggestions? export function onClick(name: string, price: string) { let data = { name: n ...

When a new VueJS project is created, it failed to automatically install the necessary basic HTML files and folders

Hey there, I am completely new to Vue.js. Just recently, I installed the Vue.js/CLI and created a brand new project using vue create test. This prompted me to choose from three options: > Default ([Vue 2] babel, eslint) Default (Vue 3 Preview) ([Vue 3 ...

I'm puzzled as to why the banner text for my three images in the slider is only displaying on one of the images, all crammed together

Currently, I am working on an ecommerce project with Next.js. One of the challenges I faced was while setting up my banner page that includes a react-slick slider for images. Initially, when I added just one image, I noticed multiple renderings of it, but ...

I am looking for a string with this particular format in JavaScript

I am working with a JSON string array that looks like this: var dataMaster = [ {"id":1,"name":"John Doe","age":30}, {"id":2,"name":"Jane Smith","age":28} ] If you want to see how I would like to transform this data, please visit the following lin ...

NodeJS Express throwing error as HTML on Angular frontend

I am currently facing an issue with my nodejs server that uses the next() function to catch errors. The problem is that the thrown error is being returned to the frontend in HTML format instead of JSON. I need help in changing it to JSON. Here is a snippe ...

Getting the most out of setInterval() - a guide in jQuery

I am currently working on an auto slide feature and could use some guidance with setInterval(). From my understanding, setInterval() is used to repeat functions infinitely, which is exactly what I need for this project. Here is the current layout: HTML & ...

Ensure that modifications to the table are saved using an ajax-generated field

I'm currently working on implementing a dynamic form that allows an administrator to add new entries into a MySQL table by clicking the add button ( + ). However, I am facing an issue where the added line appears inactive. Despite entering data into t ...

Attempting to evenly distribute images using CSS styling

I am attempting to design a slideshow with small images evenly distributed horizontally on each slide. I came across an intriguing technique on css-tricks.com and a very straightforward working example, but I have not been successful in replicating it. Be ...

Exploring the Differences Between Nth-CSS and Jquery

What are the advantages of using the nth function in CSS instead of applying it through jQuery, especially considering its compatibility with IE? Is it better to simply use jQuery from the start and avoid using it in a stylesheet altogether? Hopefully thi ...

Is there a directive in AngularJS that allows for binding HTML templates using ng-bind-html

I'm working on a directive that has the ability to use dynamic templates with expressions inside them. The challenge I face is if I use ng-bind-html, the expression won't be evaluated properly. On the other hand, using ng-bin-template results in ...

Design for a pop-up window displaying fields for entering both a username and

Currently, I am developing a mobile app using Ionic and I am in need of a popup window to collect two pieces of data - a username and a password. After researching several websites, I was unable to find a solution that addressed collecting two pieces of ...

Enhancing a Pie Chart Dynamically with Ajax using Highcharts

I need assistance with updating the data for the pie chart when a list item is clicked. The issue arises when using dynamic values from $cid in data.php. For example, user_student.cid = 1 works correctly, but if I use user_student.cid = $cid, it doesn&apos ...

How can I set up an automatic refresh for an angularjs iframe?

This code utilizes Angularjs and is designed to be run on a localhost server. The first part of the code can be found in index.html: <iframe src="{{Url}}" width="100%" height="500"></iframe> The second part of the code is located in app.js: ...

Troubleshooting: Django model form not triggering Jquery Ajax submit()

Despite numerous attempts and code modifications, I cannot get the submit() function to work correctly. Strangely, when using a click event instead, the callback is triggered and the ajax() function runs smoothly. Even after scouring multiple tutorials and ...

Laravel Tutorial: Utilizing for and foreach Loops to Showcase Data in Blade Template

I am trying to use a for and foreach loop to display data based on a template table. However, I am running into an issue where the else conditions always display an index of their own. My expectation is as follows: https://i.stack.imgur.com/tqDSn.png Th ...

Displaying the items in ng-repeat using Laravel in AngularJS

I have been encountering difficulties displaying the contents of ng-repeat while working with Laravel 5.2. If you haven't tried this before, let me explain that when using double curly braces (e.g. {{ value }}) in Angular controllers within Laravel, ...

Add two columns for mobile devices in the Woocommerce platform

How can I display 2 columns of products in my Woocommerce shop using a child theme based on 'Shopisle'? Is a CSS-only solution the best approach for this task, and will it work smoothly without any bugs? I suspect that the theme is built on Boot ...