Instructions on toggling button visibility based on dropdown selection?

My goal is to have a button hidden by default, and when I select an option from a dropdown list, the button should appear.

Check out the code on JSFIDDLE

$(function() {
  $('#cashbill').change(function() {
    $('#bill_icon').hide();
    $('#bill_icon' + $(this).val()).show();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-4" style="margin-bottom: 0px;">
  <label class="col-sm-12 control-label p-sm-0">Bill type :</label>
  <select class="form-control selectsch_items" name="cashbill" id="cashbill" required>
    <option value="">Choose an items</option>
    <option value="1">Raw</option>
    <option value="2">Spare</option>
    <option value="3">Others</option>
  </select>
</div>

<div class="form-group cash-billbtn">
  <label class="col-sm-12 control-label p-sm-0"></label>
  <button type="button" class="bill-btn" id="bill_icon">Bill</button>
</div>

I attempted to use jQuery to achieve this functionality, but it didn't work as expected.

Answer №1

To start, simply hide the button and then use the length of the selected value to determine whether to show or hide it:

$(this).val().length ?  $('#bill_icon').show() :  $('#bill_icon').hide();

Refer to the snippet below for more details:

$(function() {
 
  $('#bill_icon').hide();
  $('#cashbill').change(function() { 
     $(this).val().length ?  $('#bill_icon').show() :  $('#bill_icon').hide();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-4" style="margin-bottom: 0px;">
  <label class="col-sm-12 control-label p-sm-0">Bill type :</label>
  <select class="form-control selectsch_items" name="cashbill" id="cashbill" required>
    <option value="">Choose an items</option>
    <option value="1">Raw</option>
    <option value="2">Spare</option>
    <option value="3">Others</option>
  </select>
</div>

<div class="form-group cash-billbtn">
  <label class="col-sm-12 control-label p-sm-0"></label>
  <button type="button" class="bill-btn" id="bill_icon">Bill</button>
</div>

If you prefer to check based on the text value rather than the option value, you can use the following snippet:

$(function() {
 
  $('#bill_icon').hide();
  $('#cashbill').change(function() { 
    var text = $(this).children("option:selected").text();
   ( text == "Raw" || text == "Spare"  )?  $('#bill_icon').show() :  $('#bill_icon').hide();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-4" style="margin-bottom: 0px;">
  <label class="col-sm-12 control-label p-sm-0">Bill type :</label>
  <select class="form-control selectsch_items" name="cashbill" id="cashbill" required>
    <option value="">Choose an items</option>
    <option value="1">Raw</option>
    <option value="2">Spare</option>
    <option value="3">Others</option>
  </select>
</div>

<div class="form-group cash-billbtn">
  <label class="col-sm-12 control-label p-sm-0"></label>
  <button type="button" class="bill-btn" id="bill_icon">Bill</button>
</div>

Answer №2

One way to achieve this functionality is using jQuery:

$(document).ready(function() {
    $('#bill_icon').hide();

  $('#cashbill').change(function() {
    if (this.value) $('#bill_icon').show();
    else $('#bill_icon').hide();
  });
});

However, there are some drawbacks to this approach: - If the page takes time to load, the button may briefly appear before hiding again (creating a flashing effect). - This solution relies on JavaScript being enabled.

A more robust solution would be to initially hide the button using CSS and then control its visibility through scripting.


Here is an alternative method I recommend for achieving this behavior:

<label>Select bill type:</label>
<select name="cashbill" id="cashbill" required>
  <option value="">Choose an option</option>
  <option value="1">Raw Material</option>
  <option value="2">Spare Parts</option>
  <option value="3">Others</option>
</select>
<button type="button">View Bill</button>

Initially hide the button with CSS and only display it when a valid option is selected:

select:invalid + button {
  display: none;
}
select:valid + button {
  display: inline-block;
}

Answer №3

One alternative method involves utilizing the toggleClass function in jQuery:

  1. Start by adding the hidden class to the button, which will initially hide it.
  2. Then, incorporate the toggleClass function within the change event of the select element like so:

    $('#cashbill').change(function() {
        $('#bill_icon').toggleClass('hidden', $(this).val() === '');    
    });
    

This approach essentially prevents the toggling of the class when a selected item is not the first one.

To see this method in action, check out the live example on JSFiddle.

Answer №4

Include the following CSS code above in your file:

.bill-btn{
display: none;
}

Modify your jQuery script as shown below:

$(function() {
  $('#cashbill').change(function() {
    if($(this).val() != "others"){
      $('#bill_icon').hide();
      $('#bill_icon' + $(this).val()).show();
      $(".bill-btn").show(); // Include this line to show the button
    }
  });
});

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

Error 304 returned by Firebase cloud function causing auto-restart

For the past few months, I've been struggling with a particular issue. I've made several adjustments to the function, but nothing major. The problem lies within my https cloud function, which is designed to end a session and calculate a bill base ...

I can't seem to retrieve any values from the API other than "chicken"

Is there a way to make the search bar in my recipe app look for recipes that I provide, rather than fetching data from useState? Any suggestions on how I can achieve this? import React, { useEffect, useState } from 'react'; import Recipe from &ap ...

Leveraging $_POST data in embedded CSS styling

Can I use a PHP variable in inline CSS code? In the CSS section below, I have tried to incorporate a PHP variable: <style> p { text-align: center; } img{ -moz-animation:<?php $_POST["rmp"]; ?>s rotateRight infinite li ...

Transform the Node.js requests for both GET and POST methods to utilize Ajax

I am new to JavaScript and am currently learning how to send requests from a Node.js backend using Ajax for GET/POST operations. My backend is connected to a MySQL database and I have been studying some tutorials to gain a better understanding. Here is an ...

Internet Explorer does not support Ajax jQuery

Hello everyone. I have a js/ajax script that works fine with Firefox but not in Internet Explorer. By the way, in the head tag, I am using the following: $(document).ready(function () { //Check if url hash value exists (for bookmark) $.history.i ...

Is it possible to have an object nested within a function? How about a function within a function? I'm determined to grasp

0 Can someone explain to me how the function express() works? I'm having trouble understanding how you can call a function when stored in a variable like const app = express(); Then calling a function like listen() as if it were an object: app.list ...

Getting the jQuery selector result into the routevalues object for @Ajax.ActionLink: How can it be done?

Here is the code for an @Ajax.ActionLink I am working with: @Ajax.ActionLink("Assign Ownership", "AssignOwnership", new { techLogCode = Model.TechLog.Code, salesRepId ...

When using HTML and PHP, do note that the function mysql_fetch_array() requires the first parameter to be a resource and

I'm currently working on developing a feature for our website that allows users to search for banned usernames on our servers. The idea is to create a simple form where users can enter the username they want to check and then display any matching resu ...

How to style a triangle-shaped border with CSS transparency

I'm on a quest to create a border with a dynamic triangle effect. So far, I've managed to achieve a basic gradient effect, resulting in the following design: Check out my current design in action However, the background features a gradient that ...

<ul> hover effect and text </ul>

Looking for a solution to activate hover state on both the box and text when rolling over tiled images with text underneath. Check out this example in the Fiddle: http://jsfiddle.net/techydude/GF8tS/ Any suggestions on how I can achieve this effect? ...

What are the steps to retrieve all memcached information using node.js?

One of my main objectives is to have the user session data expire when they close their browser. However, I am facing a challenge because my Server depends on memcached to function correctly. Therefore, I need to find a way to specifically delete the use ...

Strategies for preventing the appearance of empty rows associated with unused <tr> elements

I currently have multiple asp.net panel controls that I am displaying using an html table. These panels are initially set to visible = false, but depending on the data retrieved from the database, some of the panels will be made visible. The issue arises w ...

Remove HTML tags from a table cell containing a combination of radio buttons and labels

Javascript Function: My JavaScript function posted below is designed to iterate through the column indexes specified in the 2nd parameter and also iterate through the element ids provided in the 3rd parameter. It will then populate the textbox, radiobutto ...

Ember controller failing to update template upon property set within promise execution

I am facing an issue while integrating user login functionality in my application. After retrieving the user data from the server, I aim to display the user's name on the page once the process is completed. The login form appears as a popup window, in ...

Expanding a collection of text inputs on-the-fly (HTML/JavaScript)

Looking to streamline our data entry process, I am developing an app for in-house tasks. Our team will be required to input information about various "items" that correspond to multiple "categories." To facilitate this task efficiently, I'm explorin ...

Search for objects in the array that have the same name, and then combine the values of those matching

I've done some research on various platforms, but haven't come across a solution to my specific issue. I'm looking to extract objects from an array and group them by their names in order to calculate the total hours for each matching object. ...

Issue with VueJS: Child method not getting executed when passed to parent

Within this context, the parent element is transmitting the name and age props to the child component. The child then emits a customized event called changeAgeFn which transfers its changeAge method back to the parent. In the parent component, the passed ...

Is there a way to access a comprehensive list of all the font names stored on my personal computer?

I'm currently working on a project that requires using local fonts only. Since I am using a Mac, I have located the fonts in /Library/Fonts. However, I have encountered an issue when trying to use a font named 华文黑体 directly in my CSS property: ...

What is the best way to reset the selected option in Vue.js when clicking on a (x) button?

Is there a way to create a function or button specifically for clearing select option fields? I attempted using <input type="reset" value="x" /> However, when I clear one field, all fields end up getting cleared. Should I provide my code that incl ...

The relative pathway is functional for displaying images in the CSS file, however, it does not work in the

Okay, I am going to rewrite this... I am currently working on a project that consists of two layers. The top layer involves HTML5 animations such as rollovers and slides, while the bottom layer features kaleidoscope animation using images and CSS. The is ...