Having difficulty displaying the div with jquery when a specific option is selected

This text is placed in the header section

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

Now this content is within the body of the document

<select name="product" id="product">
<option value="1">Choose Your Product</option>    
<option value="2">On Grid Power Solution</option>
<option value="3">Off Grid Energy System</option>
<option value="4">Solar Water Pump [Irrigation]</option>    
<option value="5">Solar Water Heater Installation</option>    
<option value="6">Online UPS Setup</option>    
<option value="7">Residential UPS Backup Solutions</option>
<option value="8">Inverter for Generator Replacement </option>
<option value="9">Energy Efficient LED Lighting Products</option>
<option value="10">Powerplant Leasing with ESCOMs</option>
<option value="11">Installation of Online UPS Units</option> 
    </select>
 <input type="file" name="file_attach[]"  />

The following script is located outside the body tags

      <script type="text/javascript">
  $(document).ready(function() {
    $("#product").change(function() {

      
      if ($("#product option[value='2']").attr('selected')) {
         $('.file_attach').css('display','block');

      }
        else{
        $('.file_attach').css('display','none');
        }
    }); 
  });
</script>

Whenever a selection is made, it triggers an action to hide the file attachment input.


Answer №1

Retrieve the selected value using .val() function

$("#product").change(function () {
    if ($(this).val() == "2") {
        $('.file_attach').css('display', 'block');
    } else {
        $('.file_attach').css('display', 'none'); 
    }
});

Add a class to the element

<input type="file" name="file_attach[]" class="file_attach" />

$("#product").change(function() {
  if ($(this).val() == "2") {
    $('.file_attach').css('display', 'block');
  } else {
    $('.file_attach').css('display', 'none');
  }
});
.file_attach {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="product" id="product">
    <option value="1">Select Your Product</option>    
    <option value="2">On Grid</option>
    <option value="3">Off Grid</option>
    <option value="4">Solar Water Pump [Irrigation]</option>    
    <option value="5">Solar Water Heater </option>    
    <option value="6">Online UPS </option>    
    <option value="7">Residential UPS</option>
    <option value="8">Generator Replacement Lifts Inverter </option>
    <option value="9">Energy Efficient LED'S </option>
    <option value="10">Powerplant IMC Leizning with ESCOMs</option>
    <option value="11">Online UPS Installation </option> 
</select>
<input type="file" name="file_attach[]" class="file_attach" />

Answer №2

Make sure to include the specified class in the input field:

<input type="file" name="file_attach[]" class="file_attach" />

Answer №3

Here are 3 modifications to make:

  1. Utilize the .val() method to retrieve the value of a select element
  2. Add the class file_attach to the input field
  3. Initially conceal the input field

$(document).ready(function() {
  $("#product").change(function() {
    if ($("#product").val() === "2") {
      $('.file_attach').css('display', 'block');

    } else {
      $('.file_attach').css('display', 'none');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="product" id="product">
<option value="1">Select Your Product</option>    
<option value="2">On Grid</option>
<option value="3">Off Grid</option>
<option value="4">Solar Water Pump [Irrigation]</option>    
<option value="5">Solar Water Heater </option>    
<option value="6">Online UPS </option>    
<option value="7">Residential UPS</option>
<option value="8">Generator Replacement Lifts Inverter </option>
<option value="9">Energy Efficient LED'S </option>
<option value="10">Powerplant IMC Leizning with ESCOMs</option>
<option value="11">Online UPS Installation </option> 
    </select>
<input type="file" class="file_attach" style="display:none" name="file_attach[]" />

Answer №4

Give this a try:

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

            <select name="product" id="product">
    <option value="1">Choose Your Product</option>    
    <option value="2">Grid On</option>
    <option value="3">Grid Off</option>
    <option value="4">Solar Water Pump [Irrigation]</option>    
    <option value="5">Solar Water Heater </option>    
    <option value="6">Online UPS </option>    
    <option value="7">Residential UPS</option>
    <option value="8">Inverter for Generator Replacement Lifts</option>
    <option value="9">Energy Efficient LED'S </option>
    <option value="10">Powerplant IMC Leizning with ESCOMs</option>
    <option value="11">Online UPS Installation </option> 
        </select>
     <input type="file" name="file_attach[]" class="file_attach" />

          <script type="text/javascript">
      $(document).ready(function() {
        $("#product").change(function() {
           
          if ($("#product").val() == "2") {
             $('.file_attach').css('display','block');
              
          }
            else{
            $('.file_attach').css('display','none');
            }
        }); 
      });
    </script>

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

Can the FB status update popup be displayed when clicked?

I've implemented a code on my website that allows users to update their Facebook status directly from the page: <head> <title>My Awesome Site</title> </head> <body> <div id="fb-root"></div> <script s ...

The quantity of elements stays constant even after adding to them using Javascript

I have implemented a notes list feature that allows users to add notes using an input field. Beneath the notes list ul, there is a message showing the total number of notes: $('li').length. However, I encountered an issue where the count of not ...

Slide up using jQuery to the left direction

I am looking to design a weekly calendar that slides the old week left or right when switching to a new week. Does anyone have any suggestions on how I can implement this feature? I'm currently struggling to come up with a good solution. Any help is ...

Guide to Building a Vue Checklist Calendar

My goal is to develop a straightforward ordering schedule checklist for each meal of the day by utilizing Vue.js CDN and Laravel as my backend. I expected that selecting All on Monday breakfast would also mark snack, but instead, all checkboxes are marked ...

ways to modify hash URLs using JavaScript

I am looking to add separate hash links for my Facebook and Instagram social media pages. I also want to change the text color to blue for Facebook and yellow for Instagram. How can I achieve this using JavaScript? let socialMediaData = [{ s_media: &apo ...

Guide on excluding the <src and <href tags from a JSON response in Blogger

"content": "\u003cvideo controls width=800 autoplay\u003e\n \u003csource src=\"https://srv-file8.gofile.io/download/AEiT5Y/www.4MovieRulz.ch - Sunny Winter (2020) 720p Hindi Part-2 HDRip x264 AAC 500MB.mkv&bs ...

Chrome's navigation zoom feature enhances the user experience by allowing for easy

My website has a responsive layout that functions perfectly on mobile Safari (iOS), but I've encountered an unusual issue when using Chrome on Android. Whenever I click on a link in the vertical navigation that is not at the end, Chrome opens a sort o ...

Creating product cards with equal heights in Bootstrap 5 is a simple and effective way

Any ideas on how to achieve equal height for product cards? Flex doesn't seem to be doing the trick. .product-card { position: relative; padding: 1px; display: -ms-flexbox; display: flex; -ms-flex-direction: column; flex-direction: column; ...

Expanding an array using an asynchronous operation

Let's say we have an array called file_urls containing URLs of files that we want to parse through and add the results to a final result array: var requestImageSize = require('request-image-size'); function parse_file(file) { return ne ...

Preventing Users from Inserting White Spaces in Input Fields Using the jQuery Validate Plugin

Is there a way to prevent users from inserting white-spaces in my input field? (I am using the jquery.validate.js plugin) For example: User cannot input white-spaces: John Pitt My User can input without white-spaces:JohnPittMy Edit: Using regex in ...

Tips for troubleshooting Grunt in PHPStorm (or WebStorm)

Looking for tips on debugging grunt, such as using an event listener function, in PHP Storm. Does anyone have any ideas? I know that PHP Storm has Node.js support, but I'm not sure how to configure debug settings for debugging a grunt task. For examp ...

Problems with alignment in Bootstrap4

I am currently using bootstrap 4 to style my website, and I am facing an alignment issue. I want my buttons to be aligned parallel to the date and time fields located above them. The Blue cross in the image indicates where my buttons are starting from, wh ...

When a sibling div element contains only <a href> tags, the HTML div element does not create a new line

I am just starting to learn HTML and CSS. In my first div, I want to display different elements, and in the second div, I would like to have text displayed over a background image. However, currently the text is appearing on top of the image. I want the t ...

Extracting information from XML and showcasing it in an HTML format

My current setup includes two hard-coded boxes from line 18 to line 70 in the HTML section. Now, I have an .XML file containing: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <collection> <beanRepresentation> <beanRepId> ...

Tips for choosing options from interactive drop-down menus with watir

Seeking to streamline the login process, I am looking to automate the generation of a list of databases using specified username and password credentials. I attempted the following approach: Browser.text_field(:id,"comboDatabase").when_present.set "(tas01 ...

Unlocking the Power of Typescript and ReactJS: Maximizing Efficiency with Previous State

I'm encountering difficulties implementing the previous state in React 18 with Typescript version 4.8.3. Here is my refreshToken code and I'm receiving the following error: Value of type '(prev: any) => any' has no properties in c ...

Ways to apply distinct styles to various ids and common classes

When dealing with multiple IDs such as id1, id2, and id3 that share common classes like .selectize-input and .select-dropdown, it can become cumbersome to set styles individually for each ID. Instead of writing: #id1 .selectize-input, #id2 .selectize-inp ...

"Bootstrap Toggle malfunctioning when switching between disabled and enabled states on a restricted set of

Having an issue with the Bootstrap Toggle Library in combination with Bootstrap 4. I am trying to restrict users from switching 'ON' more than a set number of elements. Here is the snippet of my HTML code: <div style="border:solid border-widt ...

How can I use Google Apps Script to convert the month name in a cell formatted as "MMMM" to uppercase in Google Sheets?

I have a cell that displays the month name in date format using MMMM. How can I script to convert the month name to uppercase while keeping the cell formatted as a date? I've attempted to use toUpperCase() without success. The code snippet I'm e ...

Does Node Express call the next middleware immediately when the next function is called?

Can someone please help me grasp the concept of how the next function operates within the Node Express framework? I know that we utilize the next function within the current middleware to trigger the execution of the subsequent middleware listed. These mid ...