How to consistently hide a div with jQuery when a select option is changed

I'm encountering an issue with hiding a div using select and onchange function. Even though the jQuery function I've written is correctly showing and hiding the div based on select option values, when I revisit the page, the div is still displayed even if the select option should hide it.

Is there a way to check the value of the select option when the page loads and adjust the display of the div accordingly?

Below is my HTML code snippet:

<select name="cancelation" class="dropdown">
   <option value="refundable">Refundable</option>
   <option value="non-refundable">Non-Refundable</option>
</select>

<div class="row cancelationDaysRow">
    <span class="no-margin-left">Up to</span>
        <div class="input-holder"><input name="cancelationDays" id="cancelation" 
             title="<?php echo $this->__('Cancelation days') ?>" 
             placeholder="<?php echo $this->__('30') ?>" value="30" 
             class="input-text input-text_inner" type="text" 
             onkeyup="this.value=this.value.replace(/[^\d]/,'')" maxlength="3"/>
        </div>
    <span>days before the starting date of this tour</span>
</div>

Here is the jQuery function I'm using:

 l$('#addTourForm select[name="cancelation"]').on('change', function(){
        $value = l$(this).val();
        //console.log($value);
        if($value == 'refundable'){
            l$('.cancelationDaysRow').css('display', 'inline-block');
        }else{
            l$('.cancelationDaysRow').css('display', 'none');
        }
    });

UPDATE When changing the select values, I encountered an error in the console: Uncaught SyntaxError: Unexpected token .ListPicker._handleMouseUp @ about:blank:502

Answer №1

Simply initiate a change event on the select element.

For example, you can use .change() or .trigger("change"):

$('#tourSelection select[name="cancellation"]').on('change', function(){
    $value = $(this).val();
    
    if($value == 'refundable'){
        $('.cancellationDetails').css('display', 'block');
    }else{
        $('.cancellationDetails').css('display', 'none');
    }
}).change();

Check out this demo where "Non-refundable" is pre-selected:

http://jsfiddle.net/UniqueCoder123/abcdefg/

Important Points:

  • To prevent any visual issues upon page loading, consider initially hiding the div and revealing it when necessary after DOM ready to avoid a momentary flicker of visibility during page load.
  • Your code snippet does not specify where the jQuery script is executed, but it's typically inside a document ready function like
    jQuery(function(){ // Your code here });

For instance:

$(function(){
    $('#tourSelection select[name="cancellation"]').on('change', function(){
        $value = $(this).val();
        
        if($value == 'refundable'){
            $('.cancellationDetails').css('display', 'block');
        }else{
            $('.cancellationDetails').css('display', 'none');
        }
    }).change();
});
  • You can simplify your code by using the toggle method with a boolean parameter:

For example:

$('#tourSelection select[name="cancellation"]').on('change', function () {
    $('.cancellationDetails').toggle($(this).val() == 'refundable');
}).trigger('change');

Answer №2

For optimal display, it is recommended to initially hide your div using inline CSS with the style attribute set to "display:none".

<div class="row cancelationDaysRow" style="display:none">
   <span class="no-margin-left">Up to</span>
    <div class="input-holder"><input name="cancelationDays" id="cancelation" 
         title="<?php echo $this->__('Cancelation days') ?>" 
         placeholder="<?php echo $this->__('30') ?>" value="30" 
         class="input-text input-text_inner" type="text" 
         onkeyup="this.value=this.value.replace(/[^\d]/,'')" maxlength="3"/>
    </div>
   <span>days before the starting date of this tour</span> </div>

Hopefully, this suggestion proves to be useful!

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

"Issues with Angular ng-show Functionality on Internet Explorer Versions 7 and

I'm currently working on a feature where I need to show or hide two divs conditionally using ng-show based on the completion of an AJAX call. The layout for this includes: <div id="div1" ng-show="!loadingData"> <!--Some markup here--> ...

`A mistake occurred while building in the package.json file`

While attempting to run all build processes by using the command npm run build:css, I encountered an error indicated below. Even after running npm cache clean --force, the issue remains unresolved. https://i.sstatic.net/4edDo.png npm ERR! code ELIFECYCLE ...

Libraries using the bootstrap slider are revolutionizing the design of all other layouts

Currently, I am utilizing a slider sourced from the following location: https://codepen.io/kravisingh/pen/pLGzgo Here is the complete code for the page: paste.ofcode.org/Dx5NyPRunupjL6GRysUx9g However, upon adding these libraries, the layout of other s ...

Exploring Vaadin 14 Slider Components

I'm looking for help on how to incorporate a slider into my Vaadin 14 project. I discovered that the slider component was removed in Vaadin 10, so I turned to this alternative: Once I added the Maven dependency and repository to my pom.xml, I success ...

What is the best method for creating uniform cards with different amounts of text that won't cause overflow issues?

At the moment, I have a container that acts as a boundary for a group of cards: .cards-container { display: flex; align-items: stretch; justify-content: center; flex-wrap: wrap; margin-top: 20px; border: 5px solid violet; } .card { ...

Mozilla puts an end to the default behavior of parent anchor tags

I am working with HTML code. In my HTML, the parent element is an anchor tag and the child element is a dropdown. I am trying to prevent the parent's default behavior. For example, when a user clicks on the dropdown, I want to trigger the dropdown ...

Exploring the Process of Iterating Through a JSON Array in Angular

Within my angular application, I am utilizing an API to retrieve data regarding a chosen country. However, I am encountering difficulties in showcasing the "name" property from the languages section within the response data: [{ "name": "Colombia", ...

A POST request to Ajax results in a bad request error code (400)

I am looking for assistance with an ajax call that is not working as expected. I'm having trouble understanding why this is happening. Could someone please review my code and provide some insight? It appears that the call is not reaching the control ...

Why are my AngularJs elements not appearing in the print dialog window?

Whenever I try to open the print Dialogue on a specific page, all I'm seeing is a blank screen. The majority of the content on this page consists of AngularJS elements. To trigger the print dialogue, I use the following code: <a href=""onclick="wi ...

How to resolve: Preventing Ajax - Post request from executing repetitively

I am facing an issue with a table that is formatted using the Datatables script. There is a column in the table which contains icons for actions. When a user clicks on an icon, a modal is loaded and its content is fetched using the POST method. The modal ...

Mastering the art of combining images and text harmoniously

I am having trouble aligning my lion image and h1 tag side by side. There seems to be an issue but I can't figure out what it is. h2 { width:50%; float:right; padding:30px 0px 0px 0px; margin:0 auto; } .lion { width:10%; float: left; paddin ...

Code not functioning properly in Internet Explorer

In one of my JavaScript functions, I have the following CSS line which works well in all browsers except for IE (Internet Explorer). When the page loads, the height of the element is only about 4px. element.setAttribute('style', "height: 15px;") ...

Exploring the Scope of LocalStorage in Javascript

I've recently begun working with local storage and encountered some scope issues. Whenever I try to console.log(test), the second if statement returns undefined. What am I missing here? This is my current code; $("document").ready(function(){ ...

The document ready event does not fire upon page load, but can be triggered using the Developer Tools Console

When the ajax call is successful, the li element gets added to the ul. $.ajax({ .. success: function (response) { response.data.forEach(function (x) { $("#ulMain").append('<li class="liSub">' + x + &apo ...

Guide on grabbing characters/words typed next to # or @ within a div element

Within a div element, I have enabled the contenteditable property. My goal is to capture any text input by the user after typing '#' or '@' until the spacebar key is pressed. This functionality will allow me to fetch suggestions from a ...

Create a shiny application that makes text bold in the user interface

Can someone please guide me on how to make specific words bold in a sentence within the UI using HTML tags under the h() function? Your assistance is greatly appreciated. Thank you. library(shiny) ui <- navbarPage( title = 'Benvenuto&apos ...

Customizing listview appearance in asp.net with css and enhancing with javascript

When I print, the css class is not being used although it appears when using the program <script type="text/javascript"> function printDiv() { var divToPrint = document.getElementById('DivIdToPrint'); ...

switching back and forth in AngularJS

Looking for help with migrating a JQuery snippet to AngularJS. $('.halfonoff').click(function(){ $('.halfonoff').removeClass('active'); $(this).addClass('active') }) Check out the example here: http://jsfidd ...

Creating an adaptable image with CSS or Material UI

Is it possible to create a responsive image that shifts from the top right position to the bottom as the size decreases? I've been using Material UI but haven't found any guidance on how to achieve this. .my-photo{ height: 300px; positio ...

Discover the visibility of an element through monitoring DOM manipulation with Selenium

Is it possible to monitor a webpage for events such as when an element becomes visible? Can this be achieved using Selenium? For instance, if I set a timeframe to watch a webpage from startTime to endTime, various page events could be recorded, including ...