Adjusting the Style of a Parent Element Depending on the Content of its Child Element

I'm currently working on changing the visibility of the second div that has the class .form-group. I'm using jQuery to get the selected option value and then adjust the visibility based on that value.

If the value is 0, then the second div .form-group should appear visible. I've faced some challenges with this task and have attempted to use parents() and closest(), but I think my implementation has been incorrect.

Below is the HTML snippet for context:

<div class="form-group">
    <label class="control-label required" for="userQuestions[1]">Do you have any dietary requirements? <span class="required">*</span></label><select class="form-control user-success" id="userQuestions_1" name="userQuestions[1]" required="required">
        <option value="">
            Please select
        </option>
        <option value="0">
            Yes
        </option>
        <option value="1">
            No
        </option>
    </select>
</div>

<div class="form-group">
    <label class="control-label" for="userQuestions[2]">Would you like to stay for after conference drinks?</label><select class="form-control" id="userQuestions_2" name="userQuestions[2]">
        <option value="">
            Please select
        </option>
        <option value="0">
            Yes
        </option>
        <option value="1">
            No
        </option>
    </select>
</div>

And here's the jQuery code snippet:

$(document).ready(function(){
    $('#useQuestion[1]').change(function(){
    if($(this).val() == '0'){ 
        $('.form-group:nth-of-type(2)').addClass('visible');
    }
    });
});

Lastly, the corresponding CSS styles are as follows:

.form-group:nth-of-type(2) {
    visibility: hidden;
}
.visible {
    visibility: visible !important;
}

Answer №1

Remember to update your function by changing ('#useQuestion[1]') to ('#userQuestions_1')

I have made the necessary modifications to your code, please see below

$(document).ready(function(){
    $('#userQuestions_1').on('change',function(){
    if($(this).val() == '0'){ 
        $('.form-group:nth-of-type(2)').addClass('visible');
    }
    });
});
.form-group:nth-of-type(2) {
    visibility: hidden;
}
.visible {
    visibility: visible !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="form-group">
    <label class="control-label required" for="userQuestions[1]">Do you have any dietary requirements? <span class="required">*</span></label><select class="form-control user-success" id="userQuestions_1" name="userQuestions[1]" required="required">
        <option value="">
            Please select
        </option>
        <option value="0">
            Yes
        </option>
        <option value="1">
            No
        </option>
    </select>
</div>

<div class="form-group">
    <label class="control-label" for="userQuestions[2]">Would you like to stay for after conference drinks?</label><select class="form-control" id="userQuestions_2" name="userQuestions[2]">
        <option value="">
            Please select
        </option>
        <option value="0">
            Yes
        </option>
        <option value="1">
            No
        </option>
    </select>
</div>

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

Whenever I create the code using javascript, padding seems to always show up

I have a basic stacked row layout that displays an upper box and lower box without any padding. <span id="route" class="small"> <div class="row" style="border-style:solid;"> <div class="col-md-12 col-12"> <p>UpperBox</p& ...

Error in three.js: Attempting to access the 'rotation' property of an undefined object

As I try to animate a cube in my scene, I keep encountering an error that reads: "TypeError: Cannot read property 'rotation' of undefined." function animate() { requestAnimationFrame( animate ); render(); } ...

Replace the default disc icon with a more detailed icon for UL lists

I am working with an unordered list and I want to use <details> to show a sublist for one of the items: <ul> <li><details> <summary>details bullet</summary> <ul> <li>detail 1</li> ...

Extracting props data from a component in React.js - a step-by-step guide

I am currently developing a react.js application with react-select. I have created a dropdown menu and when an item is clicked, I need to pass that item to a function that is connected to the redux store. How can I retrieve data from a component used in re ...

Modify the CSS styling of the row number display in jqGrid

After setting the property rownumbers:true in jqGrid, I have successfully displayed row numbers. However, I am now looking to customize the CSS for this feature. Can anyone offer guidance on how to achieve this? In the provided image, the CSS for the reco ...

Modify the parameters of the apps.facebook.com URL using the Facebook API

Is there a way to modify the parameters in the URL for apps.facebook.com using JavaScript? For instance, if a user chooses a photo, can we change the URL to apps.facebook.com/myapp/?photo_id=23234? This would allow the user to easily share the link with a ...

Utilizing regular expressions to search through a .md file in JavaScript/TS and returning null

I am currently using fs in JavaScript to read through a changelog.MD file. Here is the code snippet: const readFile = async (fileName: string) => { return promisify(fs.readFile)(filePath, 'utf8'); } Now I am reading my .md file with this fu ...

Tips for utilizing the fixed position within a flexbox design

I am working on a flexbox layout with two columns. The left column needs to be fixed, while the right column should be scrollable. Can you provide some guidance on how to achieve this? Here is the code snippet that I have been using: #parent { d ...

The document does not contain any serialized JavaScript files

Hey there, I'm facing an issue with my Codeigniter and JavaScript file upload and insertion into the database. I'm not getting any response, so could you please take a look at my code and share some valuable ideas? Below are the codes for the vie ...

How can I programmatically trigger the opening of a Material-UI Accordion in ReactJS?

All of the Accordions are assigned unique IDs: const CategoryDisplay: React.FC<Props> = (props) => { ... return ( <> <Accordion id={`category-${accordion.id}`}/> </> ); }; export default CategoryDisplay ...

Challenges arising from the offset in an overflowing Div

Encountering issues with JQuery Offset when utilized within a div that has a fixed height and overflow. This particular div contains two columns, a main column and a sidebar. The objective is to have one of the sidebar divs scroll within its container unt ...

JavaScript failing to render AJAX request

I have a website that utilizes AJAX to fetch data in JSON format from the backend and then displays it on the page. The website is built using MVC .NET framework. Below is the function responsible for loading events from the backend: function initEvents( ...

Nested UI routing with hidden display

I am working on a website using AngularJS and Ui-router. Index.html <body> <a href="#">Home Page</a> <div ui-view></div> </body> Javascript: .config(function($stateProvider, $urlRouterProvider) { $statePro ...

Leveraging Angular to dynamically adjust the height of ng-if child elements based on parent

I'm struggling with a few things in my current setup. I have a view that consists of 3 states - intro, loading, and completed. My goal is to create a sliding animation from left to right as the user moves through these states. Here is the basic struc ...

The React page on localhost is displaying a void of content with just a white background, no elements are

Can someone help me figure out what I'm doing wrong with my codes? I recently used a website called robohash to generate random robot images based on the text provided. For example, robohash.org/test was utilized in my code. The command prompt indic ...

The mobile website layout appears immaculate on the emulator, but it doesn't translate well on real mobile devices

Recently, I delved into the world of html/css/javascript and decided to create a website as a way to practice my skills. However, I have come to realize that many of the methods I used are not considered best practices. I am committed to improving and will ...

What is the best way to present information retrieved from a database using ASP.NET and HTML?

I have written a query to fetch a list of items from a database: CREATE PROCEDURE dbo.GetSubjects(@DayComing varchar(10) , @UserId varchar(3)) AS IF EXISTS( SELECT Std_ID FROM Student WHERE Std_ID = @UserID) BEG ...

Extract solely the content from a span element that meets specific width requirements

Currently, I am facing an issue with a dynamically filled span that gets content added to it. Once the content reaches the width of 500px, I need to be able to read only the content within the first 300px. This content can consist of either one line or mul ...

Identify the font style of the text box and ensure that the contenteditable feature matches the appearance of the

I'm struggling to style a contenteditable element to resemble a regular textbox on my website. Can anyone help me identify the font used in this picture? I've tried several but none seem to match perfectly. https://i.sstatic.net/2aAbb.jpg The co ...

Struggling with implementing private routes in React

Currently, I am facing an issue with creating protected routes. In my project, I have a React context that provides a value of either true or false based on whether the user is signed in or not. The problem arises when trying to access the dashboard route ...