Using jQuery to locate the closest class and display a div

Currently facing an issue with toggling on my webpage. I have a series of yes and no questions, and based on the user's response, additional questions should appear. Everything was functioning properly until I needed to relocate some of these questions within a previously answered question.

This is a snippet of my HTML structure:

<div class="form-group">
    <label for="authorCover">
        Do you consider yourself amazing? (Optional)
    </label>
    <button class="btn btn-small btn-success coverBtn yesBtn">Yes</button>
    <button class="btn btn-small btn-danger coverBtn noBtn">No</button>
    <p class="clearix"></p>
    <div class="answYes">
      <label for="upload">
        Please Upload your amazing here!
      </label>
      <input type="file" class="form-control" name="upload" value="" />
    </div><!--.answYes-->
    <div class="answNo">


   <div class="form-group">
     <label for="authorCover">
        Are you awesome? (Optional)
     </label>
     <button class="btn btn-small btn-success coverBtn yesBtn">Yes</button>
     <button class="btn btn-small btn-danger coverBtn noBtn">No</button>
     <p class="clearix"></p>
     <div class="answYes">
       <label for="awesome">
        Please Upload your awesomeness here
       </label>
       <input type="file" class="form-control" name="awesome" value="" />
     </div><!--.answYes-->
     <div class="answNo">no</div>
   </div><!--.form-group-->
  </div><!--.answNo-->
</div><!--.form-group-->

Here is how my jQuery code appears:

$('.yesBtn').on('click', function(){
  $(this).parent().find('.answYes').toggle();
  $(this).parent().find('.answNo').hide();
  return false;
});

$('.noBtn').on('click', function(){
  $(this).parent().find('.answNo').toggle();
  $(this).parent().find('.answYes').hide();
  return false;
});

If you'd like a clearer visualization, check out this jsFiddle http://jsfiddle.net/pusKM/

Your assistance on this matter would be greatly appreciated!

Answer №1

Consider utilizing .closest('.form-group') in place of .parent()

$('.yesBtn').on('click', function () {
    $(this).closest('.form-group').find('.answYes').toggle();
    $(this).closest('.form-group').find('.answNo').hide();
    return false;
});
$('.noBtn').on('click', function () {
    $(this).closest('.form-group').find('.answNo:first').toggle();
    $(this).closest('.form-group').find('.answYes').hide();
    return false;
});

Link to jsFiddle example

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

Resizing the elements within an iframe: Troubleshooting problems with embedding Bandcamp players

My goal is to embed a Bandcamp music player on my WordPress blog page, but I'm facing a challenge. The maximum width of the current player is 700px and I need it to be 900px. After consulting with someone at Bandcamp, they directed me to the old versi ...

Using Vuejs v-for on inline elements can remove unnecessary whitespace

While iterating through an array (or object) with v-for on an inline element in VueJS, there is no whitespace rendered around the element. Consider the following example: <div id="app"> Vue Rendering<br> <a v-for="fruit in fruits" ...

Tips for including an element at the start while creating a map()

enum StatusEnum { accepted = "AC", rejected = "RJ", } const select = (Object.keys(StatusEnum) as Array<keyof typeof StatusEnum>).map((x) => ({ value: x, name: x + "_random", })) /** * Console.log(select) * [ ...

Handling exceptions in AngularJS router-ui resolve functionality

In my app, I have the parent route listed below: .state('app',{ url: '/app', templateUrl: 'views/app.html', resolve: loadSequence('modernizr','moment'), ...

The POST method in Node JS request-promises does not properly handle string inputs

When I am trying to establish a connection between my node.js module and another server, I utilize the 'request-promise' library. My implementation for posting data looks like this: rp.({ method: 'POST', headers:{ 'Conte ...

The background-color of a single child within an absolutely positioned element in Chrome may not be displayed if the element has a z-index and overflow scrolling

This test page has been created to showcase the issue: <html> <head> <style> .panel { position: absolute; width: 326px; max-height: 200px; overflow: scroll; z-index: 1000; } .item-container { width: 100%; list-style: none; ...

Transforming mp4 or Avi files into m3u8 using only node js

I'm currently exploring ways to convert a mp4 or .avi file to .m3u8 using pure node js (specifically, a Firebase Cloud Function). Does anyone have any suggestions? Thank you, but I've already attempted the following: const ffmpegInstaller = requ ...

Detecting iOS format in HTML email communications allows for a more seamless

Recently, I discovered a meta tag that removes the phone number as a link in HTML on iOS. I'm curious if this also works with HTML emails. <meta name="format-detection" content="telephone=no"> I've been using workarounds to handle address ...

Having trouble debugging JavaScript as a beginner? Unable to pull the cookie value and use it as a variable? Let's

Hello everyone, I'm new to coding and have been working on a project. However, I am facing some errors and need help debugging. I have a cookie named "country" with a value of "AZ" that I want to retrieve using JavaScript and use it in my Google Maps ...

How can I track monthly data in MongoDB using Mongoose?

My current project involves creating a demonstration using mongodb mongoose. The challenge I am facing is to generate collections based on the month such as SEP_2019, OCT_2019, and DEC_2019. However, it is important to note that all collection schemas are ...

The throttle function seems to be ineffective when I try to make changes to the state within the function itself

Here is some code. The runonce function doesn't work as intended (it should only run once every 3000ms), but if I don't update the state, it works fine. const HomeScreen = ({ navigation }) => { const [count, setCount] = useState(1) fu ...

Do not delay, MongoJS function is ready to go!

I have a function set up in my Express JS endpoint that uses 'await' to retrieve data from a Mongo DB using Mongo JS. Function:- async function getIntroducer(company){ const intro = await dbIntro.collection('introducers').findOne({c ...

Step-by-step guide on entering text into a hidden field with Selenium WebDriver and Java

I am currently utilizing WebDriver in conjunction with Java for automated testing. I have come across a hidden input field within the following HTML code: <input type="hidden" value="" name="body" id=":6b"> My challenge lies in trying to input data ...

What is the best way to retrieve the chosen table row (tr) in this situation?

I have a table displayed below: How can I retrieve the selected mobile number of the tr when a button is clicked? <table class="table table-striped table-bordered table-hover table-full-width dataTable" id="sample_2" aria-describedby="sample_2_info"&g ...

What is the best way to emphasize the current page within my Bootstrap <nav> menu?

Below is the Bootstrap code that defines our main menu navigation: <div class="col-xl-9 col-lg-9"> <div class="main-menu d-none d-lg-block"> <nav> ...

If the if logic in Express.js fails to function properly, it will consistently output the same message

Every time I run this code, it always displays the same message, even when I input different email addresses let message = ""; const findQuery = "select email from Users where email = ?"; const queryResult = await db.query(findQue ...

Develop a customizable table with spreadsheet functionalities on a Django website

I'm currently working on a project for a planning site that features a spreadsheet-style table with each day as a row and every school subject as a column. The rows represent all the days in a year, while the columns represent different school subject ...

Troubleshooting disabled CSS not functioning properly in Bootstrap date picker

I've implemented the bootstrap datepicker in my project. I have successfully restricted users from selecting dates prior to the current date by setting the minimum date option. However, there's an issue where users cannot easily distinguish betwe ...

Two scenarios for tag class and just class are considered in this discussion

FOUND THE SOLUTION. Sending a huge shoutout to @JHeth and @Marko Vucurovic for their invaluable help! This query may seem lengthy, but the concept is straightforward. Let's break it down into 2 scenarios: Scenario I <html> <head><titl ...

What is the best method to determine offsetTop in relation to the parent element instead of the top of

I have a straightforward inquiry: How can one determine the offsetTop of a child element in relation to its parent element rather than the top of the window? The definition of offsetTop indicates that it should give the distance by which a child element i ...