Having no capability to manipulate CSS using jquery

In one of my divs, the CSS is set to have display: none

.cookie_policy
{
color: white;
text-align: justify;
width: 50%;
margin: 2% 25%;
line-height: 20px;
display: block;
font-family: Arial,Helvetica,sans-serif;
font-style: italic;
display:none;
}
<div class="cookie_policy">
    content goes here
</div>

When the dropdown selection changes, I am attempting to display the div only if the dropdown value is 'GB'

$("#ddlCountry").change(function () {
                if (this.value.indexOf('gb') != -1) {
                    //$('#cookie_policy').show();
                    $("#cookie_policy").css({ 'display': 'block' });
                }
                else {
                    $("#cookie_policy").css({ 'display': 'none' });
                }
                return false;
            });

I'm having trouble figuring out where I went wrong in the code as the div is not displaying. I checked the CSS values using Firebug and noticed that the property still remains as none. I tried using jQuery's show() function but the div still isn't visible.

The version of jQuery I'm using is jquery-1.4.1.min.js

Please provide guidance on where I may be making an error

Answer №1

Make sure to use the correct selector; opt for . rather than # as you are targeting a class:

$(".ddlCountry").change(function () {
    if (this.value.indexOf('gb') != -1) {
        //$('#cookie_policy').show();
        $(".cookie_policy").css({ 'display': 'block' });
    } else {
        $(".cookie_policy").css({ 'display': 'none' });
    }
    return false;
});

Answer №2

$("#cookie_policy") refers to an id selector in your CSS, but you should use a class instead like $(".cookie_policy")

For example:

var $cookiePolicy = $('.cookie_policy');

$('#ddlCountry').change(function (ev) {
    ev.preventDefault();
    $cookiePolicy[this.value === 'gb' ? 'show' : 'hide']();
});
  1. Use === and !== for type-awareness
  2. Avoid using return false unless you intend to stop propagation; use preventDefault instead
  3. Always cache the cookie_policy selector
  4. Consider using .show() and .hide() for clearer code
  5. Avoid unnecessary use of indexOf, especially if nothing follows 'gb'

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

Heading made of ribbon without increasing the scrolling space

Incorporating a unique ribbon-style heading that stretches out from the content area on both sides to create a 3D effect using an image background without relying on CSS3 techniques. I experimented with floating elements, negative margins, and relative po ...

Show content to the right side of the division element

I would like to display the bold text up here, and this is my code: img{ margin-left:10px; } html <div id="wrap"> <img src="bg.jpg" /> <b class="name">WaqasTahir</b> </div> ...

How can I display a nested div when the parent div's v-if condition is not met?

In my project, I am utilizing Laravel 6 in combination with Vue.js 2. To iterate through users and showcase their information within div elements, I am using a for loop outlined below. The Category names are stored in user.pivot.demo2, and the users are ...

"Customizing the properties of an Angular Material mat-slide-toggle: A step-by-step

<mat-slide-toggle>Slide Me!</mat-slide-toggle> https://i.stack.imgur.com/p1hzD.png https://i.stack.imgur.com/aCzs1.png Is it possible to customize the toggle-thumb-icon to increase its length and position it at the end of the bar? ...

What is the best approach to integrating an idle timeout feature with identityserver4 and aspnet identity for a secure implementation?

Currently, I am developing a login site using IdentityServer4 (server UI) with .NET Identity in .NET Core 2.2 Razor Pages. I have implemented a javascript modal alert that notifies users of an impending idle timeout and redirects them to the logout screen ...

Having trouble with my JavaScript code in Visual Studio because of a bundler issue. It's throwing an Uncaught ReferenceError for trying to access a variable before initialization

My AJAX request looks like this: $.ajax({ method: 'GET', url: '/api/some-data', headers: { 'Content-Type': 'application/json' }, success: function(data) { if (data != null) { var userDat ...

Tips on Initiating a Phone Call using a Button Click within a Recyclerview

When using the method ACTION_CALL, I encountered a problem. Clicking the button on the first card view causes the app to call the phone number 11111111. However, clicking the button on the second card view also calls the same number 1111111. What I want i ...

External JavaScript file not executing defined function

My homepage includes a register form that should open when the register button is clicked. However, I am encountering an issue where the function responsible for opening the form from another JavaScript file is not being triggered. Here is the HTML code: ...

What steps should I take to transition my Jquery code into a StimulusJS controller for Rails 7?

I recently developed a feature that checks the validity of a discount code entered in a text field using Jquery. Now, I am keen on converting this functionality into a StimulusJS controller but I'm unsure about how to proceed. Here is my current view ...

The `parent()` method in jQuery is a powerful

Assistance Required with parent() in jQuery. I am facing an issue related to the parent() function in jQuery. I have a series of images, each paired with a form allowing users to execute actions such as modifying the image description. <div id='i ...

The dropdown menu is unable to open directly below the main menu item

How can I make the submenu open to the left when hovering over a menu point, instead of directly under it? I have tried adjusting the position attributes but haven't found the right solution yet. The closest I got was by changing the display property ...

Encountering a null sessionId exception with Selenium RC while attempting to activate the JQuery AddLocationStrategy feature

I've been struggling all day to activate JQuery locators in Selenium RC by trying various suggestions found online, but unfortunately, without any success. I followed the recommendations from this thread on enabling JQuery locators: How do I add a JQ ...

Reduce the size of a webpage by 10%

Have you ever noticed that when you press Ctrl+- on any browser, the page scales down to 90% of its original size? It actually looks nicer at 90%, so I want my webpage to default to opening at 90% instead of 100%. I've tried following common approach ...

Unable to refresh the fullcalendar section following an ajax post click

Currently developing a calendar using fullcalendar. I have created an ajax button that retrieves events from another php page. The first click on the ajax button works fine, displaying a nice month calendar with events. However, my issue arises when I cl ...

What is the best way to extract the value from a textfield and then merge it with

This is a code snippet used to retrieve data from a text field: <script type="text/javascript"> var mod=document.getElementById("mod").value; ajax(mod); function callback() { if(ajaxObj(mod) { document.getElementById( ...

Implementing a line break within a JavaScript function specifically designed for formatting images

As I am not a javascript developer, the code I have been given for debugging is somewhat challenging. The issue at hand involves an iOS module where a .js CSS file has been set up and images are loading improperly, resulting in the need for horizontal scro ...

"Transforming a static navbar to a fixed position causes the page to jump

Having some difficulty figuring this out. I'm working on a bootstrap navbar that transitions from static to fixed when the user scrolls past the logo at the top. Everything seems to be working fine, except for when the navbar reaches the top, it sudde ...

What steps should I take to ensure that flex aligns the inner-divs on the same row?

I have observed that flex can easily align input tags, regular text, and other elements perfectly on a single line with the flex-direction:row; property. However, this alignment seems to get disrupted when one of the elements is a div. For example: <ht ...

Enhance your iPhone web app with high-resolution retina images!

As I develop a mobile web application accessible on any smartphone, I have the index.html file available for review: The app includes 2 jQuery functions. One detects if the user is using an iPhone and displays a bubble with instructions to add it to the h ...

What is the convention for using one-letter function names in jQuery and JSON?

Could someone please clarify the functionality of this code snippet? One aspect that I find frustrating about this function is its use of a single-lettered name. How can I determine the purpose of this function and what triggers it to run? function ...